text:
namespace base {

namespace {

class EnvironmentImpl : public base::Environment {
 public:
  virtual bool GetVar(const char* variable_name,
                      std::string* result) OVERRIDE {
    if (GetVarImpl(variable_name, result))
      return true;

    // Some commonly used variable names are uppercase while others
    // are lowercase, which is inconsistent. Let's try to be helpful
    // and look for a variable name with the reverse case.
    // I.e. HTTP_PROXY may be http_proxy for some users/systems.
    char first_char = variable_name[0];
    std::string alternate_case_var;
    if (first_char >= 'a' && first_char <= 'z')
      alternate_case_var = StringToUpperASCII(std::string(variable_name));
    else if (first_char >= 'A' && first_char <= 'Z')
      alternate_case_var = base::StringToLowerASCII(std::string(variable_name));
    else
      return false;
    return GetVarImpl(alternate_case_var.c_str(), result);
  }

  virtual bool SetVar(const char* variable_name,
                      const std::string& new_value) OVERRIDE {
    return SetVarImpl(variable_name, new_value);
  }

  virtual bool UnSetVar(const char* variable_name) OVERRIDE {
    return UnSetVarImpl(variable_name);
  }

 private:
  bool GetVarImpl(const char* variable_name, std::string* result) {
#if defined(OS_POSIX)
    const char* env_value = getenv(variable_name);
    if (!env_value)
      return false;
    // Note that the variable may be defined but empty.
    if (result)
      *result = env_value;
    return true;
#elif defined(OS_WIN)
    DWORD value_length = ::GetEnvironmentVariable(
        UTF8ToWide(variable_name).c_str(), NULL, 0);
    if (value_length == 0)
      return false;
    if (result) {
      scoped_ptr<wchar_t[]> value(new wchar_t[value_length]);
      ::GetEnvironmentVariable(UTF8ToWide(variable_name).c_str(), value.get(),
                               value_length);
      *result = WideToUTF8(value.get());
    }
    return true;
#else
#error need to port
#endif
  }

  bool SetVarImpl(const char* variable_name, const std::string& new_value) {
#if defined(OS_POSIX)
    // On success, zero is returned.
    return !setenv(variable_name, new_value.c_str(), 1);
#elif defined(OS_WIN)
    // On success, a nonzero value is returned.
    return !!SetEnvironmentVariable(UTF8ToWide(variable_name).c_str(),
                                    UTF8ToWide(new_value).c_str());
#endif
  }

  bool UnSetVarImpl(const char* variable_name) {
#if defined(OS_POSIX)
    // On success, zero is returned.
    return !unsetenv(variable_name);
#elif defined(OS_WIN)
    // On success, a nonzero value is returned.
    return !!SetEnvironmentVariable(UTF8ToWide(variable_name).c_str(), NULL);
#endif
  }
};

// Parses a null-terminated input string of an environment block. The key is
// placed into the given string, and the total length of the line, including
// the terminating null, is returned.
size_t ParseEnvLine(const NativeEnvironmentString::value_type* input,
                    NativeEnvironmentString* key) {
  // Skip to the equals or end of the string, this is the key.
  size_t cur = 0;
  while (input[cur] && input[cur] != '=')
    cur++;
  *key = NativeEnvironmentString(&input[0], cur);

  // Now just skip to the end of the string.
  while (input[cur])
    cur++;
  return cur + 1;
}

}  // namespace

namespace env_vars {

#if defined(OS_POSIX)
// On Posix systems, this variable contains the location of the user's home
// directory. (e.g, /home/username/).
const char kHome[] = "HOME";
#endif

}  // namespace env_vars

Environment::~Environment() {}

// static
Environment* Environment::Create() {
  return new EnvironmentImpl();
}

bool Environment::HasVar(const char* variable_name) {
  return GetVar(variable_name, NULL);
}

#if defined(OS_WIN)

string16 AlterEnvironment(const wchar_t* env,
                          const EnvironmentMap& changes) {
  string16 result;

  // First copy all unmodified values to the output.
  size_t cur_env = 0;
  string16 key;
  while (env[cur_env]) {
    const wchar_t* line = &env[cur_env];
    size_t line_length = ParseEnvLine(line, &key);

    // Keep only values not specified in the change vector.
    EnvironmentMap::const_iterator found_change = changes.find(key);
    if (found_change == changes.end())
      result.append(line, line_length);

    cur_env += line_length;
  }

  // Now append all modified and new values.
  for (EnvironmentMap::const_iterator i = changes.begin();
       i != changes.end(); ++i) {
    if (!i->second.empty()) {
      result.append(i->first);
      result.push_back('=');
      result.append(i->second);
      result.push_back(0);
    }
  }

  // An additional null marks the end of the list. We always need a double-null
  // in case nothing was added above.
  if (result.empty())
    result.push_back(0);
  result.push_back(0);
  return result;
}

#elif defined(OS_POSIX)

scoped_ptr<char*[]> AlterEnvironment(const char* const* const env,
                                     const EnvironmentMap& changes) {
  std::string value_storage;  // Holds concatenated null-terminated strings.
  std::vector<size_t> result_indices;  // Line indices into value_storage.

  // First build up all of the unchanged environment strings. These are
  // null-terminated of the form "key=value".
  std::string key;
  for (size_t i = 0; env[i]; i++) {
    size_t line_length = ParseEnvLine(env[i], &key);

    // Keep only values not specified in the change vector.
    EnvironmentMap::const_iterator found_change = changes.find(key);
    if (found_change == changes.end()) {
      result_indices.push_back(value_storage.size());
      value_storage.append(env[i], line_length);
    }
  }

  // Now append all modified and new values.
  for (EnvironmentMap::const_iterator i = changes.begin();
       i != changes.end(); ++i) {
    if (!i->second.empty()) {
      result_indices.push_back(value_storage.size());
      value_storage.append(i->first);
      value_storage.push_back('=');
      value_storage.append(i->second);
      value_storage.push_back(0);
    }
  }

  size_t pointer_count_required =
      result_indices.size() + 1 +  // Null-terminated array of pointers.
      (value_storage.size() + sizeof(char*) - 1) / sizeof(char*);  // Buffer.
  scoped_ptr<char*[]> result(new char*[pointer_count_required]);

  // The string storage goes after the array of pointers.
  char* storage_data = reinterpret_cast<char*>(
      &result.get()[result_indices.size() + 1]);
  if (!value_storage.empty())
    memcpy(storage_data, value_storage.data(), value_storage.size());

  // Fill array of pointers at the beginning of the result.
  for (size_t i = 0; i < result_indices.size(); i++)
    result[i] = &storage_data[result_indices[i]];
  result[result_indices.size()] = 0;  // Null terminator.

  return result.Pass();
}

#endif  // OS_POSIX

}  // namespace base


text:
package com.dianping.cat.report.alert.sender.sender;

import java.net.URLEncoder;
import java.util.List;

import com.dianping.cat.Cat;
import com.dianping.cat.report.alert.sender.AlertChannel;
import com.dianping.cat.report.alert.sender.AlertMessageEntity;

public class SmsSender extends AbstractSender {

	public static final String ID = AlertChannel.SMS.getName();

	@Override
	public String getId() {
		return ID;
	}

	@Override
	public boolean send(AlertMessageEntity message) {
		com.dianping.cat.home.sender.entity.Sender sender = querySender();
		boolean batchSend = sender.getBatchSend();
		boolean result = false;

		if (batchSend) {
			String phones = message.getReceiverString();

			result = sendSms(message, phones, sender);
		} else {
			List<String> phones = message.getReceivers();

			for (String phone : phones) {
				boolean success = sendSms(message, phone, sender);
				result = result || success;
			}
		}
		return result;
	}

	private boolean sendSms(AlertMessageEntity message, String receiver,
	      com.dianping.cat.home.sender.entity.Sender sender) {
		String filterContent = message.getContent().replaceAll("(<a href.*(?=))|(\n)", "");
		String content = message.getTitle() + " " + filterContent;
		String urlPrefix = sender.getUrl();
		String urlPars = m_senderConfigManager.queryParString(sender);

		try {
			urlPars = urlPars.replace("${receiver}", URLEncoder.encode(receiver, "utf-8")).replace("${content}",
			      URLEncoder.encode(content, "utf-8"));
		} catch (Exception e) {
			Cat.logError(e);
		}

		return httpSend(sender.getSuccessCode(), sender.getType(), urlPrefix, urlPars);
	}
}

redpajama_set_name: RedPajamaGithub


text:
import subprocess
import os

class TimetableScraper:
    UL_TIMETABLE_FILE = "tt2.asp"
    UL_TIMETABLE_WEBSITE = "www.timetable.ul.ie/" + UL_TIMETABLE_FILE
    TMP_FILEPATH = "/tmp/"

    def __init__(self, param1):
        self.param1 = param1
        self.html = getTimetable()

    def getTimetable(self):
        subprocess.check_output("wget -P " + TMP_FILEPATH + self.param1 + "/ --post-data \"T1=" + self.param1 + "&B1=Submit\" " + UL_TIMETABLE_WEBSITE, shell=True)
        timetable_html = open(TMP_FILEPATH + self.param1 + "/" + UL_TIMETABLE_FILE).read()
        os.system("rm -rf " + TMP_FILEPATH + self.param1)
        return timetable_html


text:
namespace boost { namespace xpressive { namespace detail
{

    ///////////////////////////////////////////////////////////////////////////////
    // assert_bol_matcher
    //
    template<typename Traits>
    struct assert_bol_matcher
      : assert_line_base<Traits>
    {
        typedef typename Traits::char_type char_type;

        assert_bol_matcher(Traits const &tr)
          : assert_line_base<Traits>(tr)
        {
        }

        template<typename BidiIter, typename Next>
        bool match(match_state<BidiIter> &state, Next const &next) const
        {
            if(state.bos())
            {
                if(!state.flags_.match_bol_)
                {
                    return false;
                }
            }
            else
            {
                char_type ch = *boost::prior(state.cur_);

                // If the previous character is not a newline, we're not at the start of a line
                if(!traits_cast<Traits>(state).isctype(ch, this->newline_))
                {
                    return false;
                }
                // There is no line-break between \r and \n
                else if(ch == this->cr_ && !state.eos() && *state.cur_ == this->nl_)
                {
                    return false;
                }
            }

            return next.match(state);
        }
    };

}}}

#endif


text:
#include "SkGlyphCache.h"
#include "SkGlyphCache_Globals.h"
#include "SkGraphics.h"
#include "SkLazyPtr.h"
#include "SkMutex.h"
#include "SkPaint.h"
#include "SkPath.h"
#include "SkTLS.h"
#include "SkTemplates.h"
#include "SkTypeface.h"

//#define SPEW_PURGE_STATUS

namespace {

SkGlyphCache_Globals* create_globals() {
    return SkNEW(SkGlyphCache_Globals);
}

}  // namespace

SK_DECLARE_STATIC_LAZY_PTR(SkGlyphCache_Globals, globals, create_globals);

// Returns the shared globals
static SkGlyphCache_Globals& get_globals() {
    return *globals.get();
}

///////////////////////////////////////////////////////////////////////////////

#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
    #define RecordHashSuccess()             fHashHitCount += 1
    #define RecordHashCollisionIf(pred)     do { if (pred) fHashMissCount += 1; } while (0)
#else
    #define RecordHashSuccess()             (void)0
    #define RecordHashCollisionIf(pred)     (void)0
#endif
#define RecordHashCollision() RecordHashCollisionIf(true)

///////////////////////////////////////////////////////////////////////////////

// so we don't grow our arrays a lot
#define kMinGlyphCount      16
#define kMinGlyphImageSize  (16*2)
#define kMinAllocAmount     ((sizeof(SkGlyph) + kMinGlyphImageSize) * kMinGlyphCount)

SkGlyphCache::SkGlyphCache(SkTypeface* typeface, const SkDescriptor* desc, SkScalerContext* ctx)
        : fScalerContext(ctx), fGlyphAlloc(kMinAllocAmount) {
    SkASSERT(typeface);
    SkASSERT(desc);
    SkASSERT(ctx);

    fPrev = fNext = NULL;

    fDesc = desc->copy();
    fScalerContext->getFontMetrics(&fFontMetrics);

    // Create the sentinel SkGlyph.
    SkGlyph* sentinel = fGlyphArray.insert(0);
    sentinel->initGlyphFromCombinedID(SkGlyph::kImpossibleID);

    // Initialize all index to zero which points to the sentinel SkGlyph.
    memset(fGlyphHash, 0x00, sizeof(fGlyphHash));

    fMemoryUsed = sizeof(*this);

    fGlyphArray.setReserve(kMinGlyphCount);

    fAuxProcList = NULL;

#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
    fHashHitCount = fHashMissCount = 0;
#endif
}

SkGlyphCache::~SkGlyphCache() {
#if 0
    {
        size_t ptrMem = fGlyphArray.count() * sizeof(SkGlyph*);
        size_t glyphAlloc = fGlyphAlloc.totalCapacity();
        size_t glyphHashUsed = 0;
        size_t uniHashUsed = 0;
        for (int i = 0; i < kHashCount; ++i) {
            glyphHashUsed += fGlyphHash[i] ? sizeof(fGlyphHash[0]) : 0;
            uniHashUsed += fCharToGlyphHash[i].fID != 0xFFFFFFFF ? sizeof(fCharToGlyphHash[0]) : 0;
        }
        size_t glyphUsed = fGlyphArray.count() * sizeof(SkGlyph);
        size_t imageUsed = 0;
        for (int i = 0; i < fGlyphArray.count(); ++i) {
            const SkGlyph& g = *fGlyphArray[i];
            if (g.fImage) {
                imageUsed += g.fHeight * g.rowBytes();
            }
        }

        SkDebugf("glyphPtrArray,%zu, Alloc,%zu, imageUsed,%zu, glyphUsed,%zu, glyphHashAlloc,%zu, glyphHashUsed,%zu, unicharHashAlloc,%zu, unicharHashUsed,%zu\n",
                 ptrMem, glyphAlloc, imageUsed, glyphUsed, sizeof(fGlyphHash), glyphHashUsed, sizeof(CharGlyphRec) * kHashCount, uniHashUsed);

    }
#endif
    SkGlyph*   gptr = fGlyphArray.begin();
    SkGlyph*   stop = fGlyphArray.end();
    while (gptr < stop) {
        SkPath* path = gptr->fPath;
        if (path) {
            SkDELETE(path);
        }
        gptr += 1;
    }
    SkDescriptor::Free(fDesc);
    SkDELETE(fScalerContext);
    this->invokeAndRemoveAuxProcs();
}

SkGlyphCache::CharGlyphRec* SkGlyphCache::getCharGlyphRec(uint32_t id) {
    if (NULL == fCharToGlyphHash.get()) {
        // Allocate the array.
        fCharToGlyphHash.reset(kHashCount);
        // Initialize entries of fCharToGlyphHash to index the sentinel glyph and
        // an fID value that will not match any id.
        for (int i = 0; i <kHashCount; ++i) {
            fCharToGlyphHash[i].fID = SkGlyph::kImpossibleID;
            fCharToGlyphHash[i].fGlyphIndex = 0;
        }
    }

    return &fCharToGlyphHash[ID2HashIndex(id)];
}

void SkGlyphCache::adjustCaches(int insertion_index) {
    for (int i = 0; i < kHashCount; ++i) {
        if (fGlyphHash[i] >= SkToU16(insertion_index)) {
            fGlyphHash[i] += 1;
        }
    }
    if (fCharToGlyphHash.get() != NULL) {
        for (int i = 0; i < kHashCount; ++i) {
            if (fCharToGlyphHash[i].fGlyphIndex >= SkToU16(insertion_index)) {
                fCharToGlyphHash[i].fGlyphIndex += 1;
            }
        }
    }
}

///////////////////////////////////////////////////////////////////////////////

#ifdef SK_DEBUG
#define VALIDATE()  AutoValidate av(this)
#else
#define VALIDATE()
#endif

uint16_t SkGlyphCache::unicharToGlyph(SkUnichar charCode) {
    VALIDATE();
    uint32_t id = SkGlyph::MakeID(charCode);
    const CharGlyphRec& rec = *this->getCharGlyphRec(id);

    if (rec.fID == id) {
        return fGlyphArray[rec.fGlyphIndex].getGlyphID();
    } else {
        return fScalerContext->charToGlyphID(charCode);
    }
}

SkUnichar SkGlyphCache::glyphToUnichar(uint16_t glyphID) {
    return fScalerContext->glyphIDToChar(glyphID);
}

unsigned SkGlyphCache::getGlyphCount() {
    return fScalerContext->getGlyphCount();
}

///////////////////////////////////////////////////////////////////////////////

const SkGlyph& SkGlyphCache::getUnicharAdvance(SkUnichar charCode) {
    VALIDATE();
    return *this->lookupByChar(charCode, kJustAdvance_MetricsType);
}

const SkGlyph& SkGlyphCache::getGlyphIDAdvance(uint16_t glyphID) {
    VALIDATE();
    uint32_t id = SkGlyph::MakeID(glyphID);
    return *this->lookupByCombinedID(id, kJustAdvance_MetricsType);
}

///////////////////////////////////////////////////////////////////////////////

const SkGlyph& SkGlyphCache::getUnicharMetrics(SkUnichar charCode) {
    VALIDATE();
    return *this->lookupByChar(charCode, kFull_MetricsType);
}

const SkGlyph& SkGlyphCache::getUnicharMetrics(SkUnichar charCode,
                                               SkFixed x, SkFixed y) {
    VALIDATE();
    return *this->lookupByChar(charCode, kFull_MetricsType, x, y);
}

const SkGlyph& SkGlyphCache::getGlyphIDMetrics(uint16_t glyphID) {
    VALIDATE();
    uint32_t id = SkGlyph::MakeID(glyphID);
    return *this->lookupByCombinedID(id, kFull_MetricsType);
}

const SkGlyph& SkGlyphCache::getGlyphIDMetrics(uint16_t glyphID, SkFixed x, SkFixed y) {
    VALIDATE();
    uint32_t id = SkGlyph::MakeID(glyphID, x, y);
    return *this->lookupByCombinedID(id, kFull_MetricsType);
}

SkGlyph* SkGlyphCache::lookupByChar(SkUnichar charCode, MetricsType type, SkFixed x, SkFixed y) {
    uint32_t id = SkGlyph::MakeID(charCode, x, y);
    CharGlyphRec* rec = this->getCharGlyphRec(id);
    SkGlyph* glyph;
    if (rec->fID != id) {
        RecordHashCollisionIf(glyph_index != SkGlyph::kImpossibleID);
        // this ID is based on the UniChar
        rec->fID = id;
        // this ID is based on the glyph index
        id = SkGlyph::MakeID(fScalerContext->charToGlyphID(charCode), x, y);
        rec->fGlyphIndex = this->lookupMetrics(id, type);
        glyph = &fGlyphArray[rec->fGlyphIndex];
    } else {
        RecordHashSuccess();
        glyph = &fGlyphArray[rec->fGlyphIndex];
        if (type == kFull_MetricsType && glyph->isJustAdvance()) {
            fScalerContext->getMetrics(glyph);
        }
    }
    return glyph;
}

SkGlyph* SkGlyphCache::lookupByCombinedID(uint32_t id, MetricsType type) {
    uint32_t hash_index = ID2HashIndex(id);
    uint16_t glyph_index = fGlyphHash[hash_index];
    SkGlyph* glyph = &fGlyphArray[glyph_index];

    if (glyph->fID != id) {
        RecordHashCollisionIf(glyph_index != SkGlyph::kImpossibleID);
        glyph_index = this->lookupMetrics(id, type);
        fGlyphHash[hash_index] = glyph_index;
        glyph = &fGlyphArray[glyph_index];
    } else {
        RecordHashSuccess();
        if (type == kFull_MetricsType && glyph->isJustAdvance()) {
           fScalerContext->getMetrics(glyph);
        }
    }
    return glyph;
}

uint16_t SkGlyphCache::lookupMetrics(uint32_t id, MetricsType mtype) {
    SkASSERT(id != SkGlyph::kImpossibleID);
    // Count is always greater than 0 because of the sentinel.
    // The fGlyphArray cache is in descending order, so that the sentinel with a value of ~0 is
    // always at index 0.
    SkGlyph* gptr = fGlyphArray.begin();
    int lo = 0;
    int hi = fGlyphArray.count() - 1;
    while (lo < hi) {
        int mid = (hi + lo) >> 1;
        if (gptr[mid].fID > id) {
            lo = mid + 1;
        } else {
            hi = mid;
        }
    }

    uint16_t glyph_index = hi;
    SkGlyph* glyph = &gptr[glyph_index];
    if (glyph->fID == id) {
        if (kFull_MetricsType == mtype && glyph->isJustAdvance()) {
            fScalerContext->getMetrics(glyph);
        }
        SkASSERT(glyph->fID != SkGlyph::kImpossibleID);
        return glyph_index;
    }

    // check if we need to bump hi before falling though to the allocator
    if (glyph->fID > id) {
        glyph_index += 1;
    }

    // Not found, but hi contains the index of the insertion point of the new glyph.
    fMemoryUsed += sizeof(SkGlyph);

    this->adjustCaches(glyph_index);

    glyph = fGlyphArray.insert(glyph_index);
    glyph->initGlyphFromCombinedID(id);

    if (kJustAdvance_MetricsType == mtype) {
        fScalerContext->getAdvance(glyph);
    } else {
        SkASSERT(kFull_MetricsType == mtype);
        fScalerContext->getMetrics(glyph);
    }

    SkASSERT(glyph->fID != SkGlyph::kImpossibleID);
    return glyph_index;
}

const void* SkGlyphCache::findImage(const SkGlyph& glyph) {
    if (glyph.fWidth > 0 && glyph.fWidth < kMaxGlyphWidth) {
        if (NULL == glyph.fImage) {
            size_t  size = glyph.computeImageSize();
            const_cast<SkGlyph&>(glyph).fImage = fGlyphAlloc.alloc(size,
                                        SkChunkAlloc::kReturnNil_AllocFailType);
            // check that alloc() actually succeeded
            if (glyph.fImage) {
                fScalerContext->getImage(glyph);
                // TODO: the scaler may have changed the maskformat during
                // getImage (e.g. from AA or LCD to BW) which means we may have
                // overallocated the buffer. Check if the new computedImageSize
                // is smaller, and if so, strink the alloc size in fImageAlloc.
                fMemoryUsed += size;
            }
        }
    }
    return glyph.fImage;
}

const SkPath* SkGlyphCache::findPath(const SkGlyph& glyph) {
    if (glyph.fWidth) {
        if (glyph.fPath == NULL) {
            const_cast<SkGlyph&>(glyph).fPath = SkNEW(SkPath);
            fScalerContext->getPath(glyph, glyph.fPath);
            fMemoryUsed += sizeof(SkPath) +
                    glyph.fPath->countPoints() * sizeof(SkPoint);
        }
    }
    return glyph.fPath;
}

void SkGlyphCache::dump() const {
    const SkTypeface* face = fScalerContext->getTypeface();
    const SkScalerContextRec& rec = fScalerContext->getRec();
    SkMatrix matrix;
    rec.getSingleMatrix(&matrix);
    matrix.preScale(SkScalarInvert(rec.fTextSize), SkScalarInvert(rec.fTextSize));
    SkString name;
    face->getFamilyName(&name);

    SkString msg;
    msg.printf("cache typeface:%x %25s:%d size:%2g [%g %g %g %g] lum:%02X devG:%d pntG:%d cntr:%d glyphs:%3d",
               face->uniqueID(), name.c_str(), face->style(), rec.fTextSize,
               matrix[SkMatrix::kMScaleX], matrix[SkMatrix::kMSkewX],
               matrix[SkMatrix::kMSkewY], matrix[SkMatrix::kMScaleY],
               rec.fLumBits & 0xFF, rec.fDeviceGamma, rec.fPaintGamma, rec.fContrast,
               fGlyphArray.count());
#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
    const int sum = SkTMax(fHashHitCount + fHashMissCount, 1);   // avoid divide-by-zero
    msg.appendf(" hash:%2d\n", 100 * fHashHitCount / sum);
#endif
    SkDebugf("%s\n", msg.c_str());
}

///////////////////////////////////////////////////////////////////////////////

bool SkGlyphCache::getAuxProcData(void (*proc)(void*), void** dataPtr) const {
    const AuxProcRec* rec = fAuxProcList;
    while (rec) {
        if (rec->fProc == proc) {
            if (dataPtr) {
                *dataPtr = rec->fData;
            }
            return true;
        }
        rec = rec->fNext;
    }
    return false;
}

void SkGlyphCache::setAuxProc(void (*proc)(void*), void* data) {
    if (proc == NULL) {
        return;
    }

    AuxProcRec* rec = fAuxProcList;
    while (rec) {
        if (rec->fProc == proc) {
            rec->fData = data;
            return;
        }
        rec = rec->fNext;
    }
    // not found, create a new rec
    rec = SkNEW(AuxProcRec);
    rec->fProc = proc;
    rec->fData = data;
    rec->fNext = fAuxProcList;
    fAuxProcList = rec;
}

void SkGlyphCache::invokeAndRemoveAuxProcs() {
    AuxProcRec* rec = fAuxProcList;
    while (rec) {
        rec->fProc(rec->fData);
        AuxProcRec* next = rec->fNext;
        SkDELETE(rec);
        rec = next;
    }
}

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

class AutoAcquire {
public:
    AutoAcquire(SkSpinlock& lock) : fLock(lock) { fLock.acquire(); }
    ~AutoAcquire() { fLock.release(); }
private:
    SkSpinlock& fLock;
};

size_t SkGlyphCache_Globals::setCacheSizeLimit(size_t newLimit) {
    static const size_t minLimit = 256 * 1024;
    if (newLimit < minLimit) {
        newLimit = minLimit;
    }

    AutoAcquire ac(fLock);

    size_t prevLimit = fCacheSizeLimit;
    fCacheSizeLimit = newLimit;
    this->internalPurge();
    return prevLimit;
}

int SkGlyphCache_Globals::setCacheCountLimit(int newCount) {
    if (newCount < 0) {
        newCount = 0;
    }

    AutoAcquire ac(fLock);

    int prevCount = fCacheCountLimit;
    fCacheCountLimit = newCount;
    this->internalPurge();
    return prevCount;
}

void SkGlyphCache_Globals::purgeAll() {
    AutoAcquire ac(fLock);
    this->internalPurge(fTotalMemoryUsed);
}

/*  This guy calls the visitor from within the mutext lock, so the visitor
    cannot:
    - take too much time
    - try to acquire the mutext again
    - call a fontscaler (which might call into the cache)
*/
SkGlyphCache* SkGlyphCache::VisitCache(SkTypeface* typeface,
                              const SkDescriptor* desc,
                              bool (*proc)(const SkGlyphCache*, void*),
                              void* context) {
    if (!typeface) {
        typeface = SkTypeface::GetDefaultTypeface();
    }
    SkASSERT(desc);

    SkGlyphCache_Globals& globals = get_globals();
    SkGlyphCache*         cache;

    {
        AutoAcquire ac(globals.fLock);

        globals.validate();

        for (cache = globals.internalGetHead(); cache != NULL; cache = cache->fNext) {
            if (cache->fDesc->equals(*desc)) {
                globals.internalDetachCache(cache);
                if (!proc(cache, context)) {
                    globals.internalAttachCacheToHead(cache);
                    cache = NULL;
                }
                return cache;
            }
        }
    }

    // Check if we can create a scaler-context before creating the glyphcache.
    // If not, we may have exhausted OS/font resources, so try purging the
    // cache once and try again.
    {
        // pass true the first time, to notice if the scalercontext failed,
        // so we can try the purge.
        SkScalerContext* ctx = typeface->createScalerContext(desc, true);
        if (!ctx) {
            get_globals().purgeAll();
            ctx = typeface->createScalerContext(desc, false);
            SkASSERT(ctx);
        }
        cache = SkNEW_ARGS(SkGlyphCache, (typeface, desc, ctx));
    }

    AutoValidate av(cache);

    if (!proc(cache, context)) {   // need to reattach
        globals.attachCacheToHead(cache);
        cache = NULL;
    }
    return cache;
}

void SkGlyphCache::AttachCache(SkGlyphCache* cache) {
    SkASSERT(cache);
    SkASSERT(cache->fNext == NULL);

    get_globals().attachCacheToHead(cache);
}

void SkGlyphCache::Dump() {
    SkGlyphCache_Globals& globals = get_globals();
    AutoAcquire           ac(globals.fLock);
    SkGlyphCache*         cache;

    globals.validate();

    SkDebugf("SkGlyphCache strikes:%d memory:%d\n",
             globals.getCacheCountUsed(), (int)globals.getTotalMemoryUsed());

#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
    int hitCount = 0;
    int missCount = 0;
#endif

    for (cache = globals.internalGetHead(); cache != NULL; cache = cache->fNext) {
#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
        hitCount += cache->fHashHitCount;
        missCount += cache->fHashMissCount;
#endif
        cache->dump();
    }
#ifdef SK_GLYPHCACHE_TRACK_HASH_STATS
    SkDebugf("Hash hit percent:%2d\n", 100 * hitCount / (hitCount + missCount));
#endif
}

///////////////////////////////////////////////////////////////////////////////

void SkGlyphCache_Globals::attachCacheToHead(SkGlyphCache* cache) {
    AutoAcquire ac(fLock);

    this->validate();
    cache->validate();

    this->internalAttachCacheToHead(cache);
    this->internalPurge();
}

SkGlyphCache* SkGlyphCache_Globals::internalGetTail() const {
    SkGlyphCache* cache = fHead;
    if (cache) {
        while (cache->fNext) {
            cache = cache->fNext;
        }
    }
    return cache;
}

size_t SkGlyphCache_Globals::internalPurge(size_t minBytesNeeded) {
    this->validate();

    size_t bytesNeeded = 0;
    if (fTotalMemoryUsed > fCacheSizeLimit) {
        bytesNeeded = fTotalMemoryUsed - fCacheSizeLimit;
    }
    bytesNeeded = SkTMax(bytesNeeded, minBytesNeeded);
    if (bytesNeeded) {
        // no small purges!
        bytesNeeded = SkTMax(bytesNeeded, fTotalMemoryUsed >> 2);
    }

    int countNeeded = 0;
    if (fCacheCount > fCacheCountLimit) {
        countNeeded = fCacheCount - fCacheCountLimit;
        // no small purges!
        countNeeded = SkMax32(countNeeded, fCacheCount >> 2);
    }

    // early exit
    if (!countNeeded && !bytesNeeded) {
        return 0;
    }

    size_t  bytesFreed = 0;
    int     countFreed = 0;

    // we start at the tail and proceed backwards, as the linklist is in LRU
    // order, with unimportant entries at the tail.
    SkGlyphCache* cache = this->internalGetTail();
    while (cache != NULL &&
           (bytesFreed < bytesNeeded || countFreed < countNeeded)) {
        SkGlyphCache* prev = cache->fPrev;
        bytesFreed += cache->fMemoryUsed;
        countFreed += 1;

        this->internalDetachCache(cache);
        SkDELETE(cache);
        cache = prev;
    }

    this->validate();

#ifdef SPEW_PURGE_STATUS
    if (countFreed) {
        SkDebugf("purging %dK from font cache [%d entries]\n",
                 (int)(bytesFreed >> 10), countFreed);
    }
#endif

    return bytesFreed;
}

void SkGlyphCache_Globals::internalAttachCacheToHead(SkGlyphCache* cache) {
    SkASSERT(NULL == cache->fPrev && NULL == cache->fNext);
    if (fHead) {
        fHead->fPrev = cache;
        cache->fNext = fHead;
    }
    fHead = cache;

    fCacheCount += 1;
    fTotalMemoryUsed += cache->fMemoryUsed;
}

void SkGlyphCache_Globals::internalDetachCache(SkGlyphCache* cache) {
    SkASSERT(fCacheCount > 0);
    fCacheCount -= 1;
    fTotalMemoryUsed -= cache->fMemoryUsed;

    if (cache->fPrev) {
        cache->fPrev->fNext = cache->fNext;
    } else {
        fHead = cache->fNext;
    }
    if (cache->fNext) {
        cache->fNext->fPrev = cache->fPrev;
    }
    cache->fPrev = cache->fNext = NULL;
}

///////////////////////////////////////////////////////////////////////////////

#ifdef SK_DEBUG

void SkGlyphCache::validate() const {
#ifdef SK_DEBUG_GLYPH_CACHE
    int count = fGlyphArray.count();
    for (int i = 0; i < count; i++) {
        const SkGlyph* glyph = &fGlyphArray[i];
        SkASSERT(glyph);
        if (glyph->fImage) {
            SkASSERT(fGlyphAlloc.contains(glyph->fImage));
        }
    }
#endif
}

void SkGlyphCache_Globals::validate() const {
    size_t computedBytes = 0;
    int computedCount = 0;

    const SkGlyphCache* head = fHead;
    while (head != NULL) {
        computedBytes += head->fMemoryUsed;
        computedCount += 1;
        head = head->fNext;
    }

    SkASSERTF(fCacheCount == computedCount, "fCacheCount: %d, computedCount: %d", fCacheCount,
              computedCount);
    SkASSERTF(fTotalMemoryUsed == computedBytes, "fTotalMemoryUsed: %d, computedBytes: %d",
              fTotalMemoryUsed, computedBytes);
}

#endif

///////////////////////////////////////////////////////////////////////////////
///////////////////////////////////////////////////////////////////////////////

#include "SkTypefaceCache.h"

size_t SkGraphics::GetFontCacheLimit() {
    return get_globals().getCacheSizeLimit();
}

size_t SkGraphics::SetFontCacheLimit(size_t bytes) {
    return get_globals().setCacheSizeLimit(bytes);
}

size_t SkGraphics::GetFontCacheUsed() {
    return get_globals().getTotalMemoryUsed();
}

int SkGraphics::GetFontCacheCountLimit() {
    return get_globals().getCacheCountLimit();
}

int SkGraphics::SetFontCacheCountLimit(int count) {
    return get_globals().setCacheCountLimit(count);
}

int SkGraphics::GetFontCacheCountUsed() {
    return get_globals().getCacheCountUsed();
}

void SkGraphics::PurgeFontCache() {
    get_globals().purgeAll();
    SkTypefaceCache::PurgeAll();
}

// TODO(herb): clean up TLS apis.
size_t SkGraphics::GetTLSFontCacheLimit() { return 0; }
void SkGraphics::SetTLSFontCacheLimit(size_t bytes) { }


text:
import DS from 'ember-data';

export default DS.Model.extend({
	name: DS.attr('string'),
	title: DS.attr('string'),
	lvlclass: DS.attr('string'),
	total: DS.attr('number'),
	comboModifier: DS.attr('number'),
	time: DS.attr('number'),
	cards: DS.hasMany('card')
});


text:
#include "libomron/omron.h"

#include <api/setupapi.h>
#include <api/hidsdi.h>
#include <stdlib.h>
#include <stdio.h>

//Application global variables
DWORD								ActualBytesRead;
DWORD								BytesRead;
HIDP_CAPS							Capabilities;
DWORD								cbBytesRead;
PSP_DEVICE_INTERFACE_DETAIL_DATA	detailData;
DWORD								dwError;
char								FeatureReport[256];
HANDLE								hEventObject;
HANDLE								hDevInfo;
GUID								HidGuid;
OVERLAPPED							HIDOverlapped;
char								InputReport[256];
ULONG								Length;
LPOVERLAPPED						lpOverLap;
BOOL								MyDeviceDetected = FALSE;
TCHAR*								MyDevicePathName;
DWORD								NumberOfBytesRead;
char								OutputReport[256];
DWORD								ReportType;
ULONG								Required;
TCHAR*								ValueToDisplay;

void GetDeviceCapabilities(HANDLE DeviceHandle)
{
	//Get the Capabilities structure for the device.

	PHIDP_PREPARSED_DATA	PreparsedData;

	/*
	  API function: HidD_GetPreparsedData
	  Returns: a pointer to a buffer containing the information about the device's capabilities.
	  Requires: A handle returned by CreateFile.
	  There's no need to access the buffer directly,
	  but HidP_GetCaps and other API functions require a pointer to the buffer.
	*/

	HidD_GetPreparsedData
		(DeviceHandle,
		 &PreparsedData);

	/*
	  API function: HidP_GetCaps
	  Learn the device's capabilities.
	  For standard devices such as joysticks, you can find out the specific
	  capabilities of the device.
	  For a custom device, the software will probably know what the device is capable of,
	  and the call only verifies the information.
	  Requires: the pointer to the buffer returned by HidD_GetPreparsedData.
	  Returns: a Capabilities structure containing the information.
	*/

	HidP_GetCaps
		(PreparsedData,
		 &Capabilities);

	HidD_FreePreparsedData(PreparsedData);
}

int omron_open_win32(omron_device* dev, int VID, int PID, unsigned int device_index, int get_count)
{
	//Use a series of API calls to find a HID with a specified Vendor IF and Product ID.

	HIDD_ATTRIBUTES						Attributes;
	SP_DEVICE_INTERFACE_DATA			devInfoData;
	BOOL								LastDevice = FALSE;
	int									MemberIndex = 0;
	LONG								Result;
	int									device_count = 0;

	Length = 0;
	detailData = NULL;
	dev->device._dev = NULL;

	/*
	  API function: HidD_GetHidGuid
	  Get the GUID for all system HIDs.
	  Returns: the GUID in HidGuid.
	*/

	HidD_GetHidGuid(&HidGuid);

	/*
	  API function: SetupDiGetClassDevs
	  Returns: a handle to a device information set for all installed devices.
	  Requires: the GUID returned by GetHidGuid.
	*/

	hDevInfo=SetupDiGetClassDevs
		(&HidGuid,
		 NULL,
		 NULL,
		 DIGCF_PRESENT|DIGCF_INTERFACEDEVICE);

	devInfoData.cbSize = sizeof(devInfoData);

	//Step through the available devices looking for the one we want.
	//Quit on detecting the desired device or checking all available devices without success.

	MemberIndex = 0;
	LastDevice = FALSE;

	do
	{
		/*
		  API function: SetupDiEnumDeviceInterfaces
		  On return, MyDeviceInterfaceData contains the handle to a
		  SP_DEVICE_INTERFACE_DATA structure for a detected device.
		  Requires:
		  The DeviceInfoSet returned in SetupDiGetClassDevs.
		  The HidGuid returned in GetHidGuid.
		  An index to specify a device.
		*/

		Result=SetupDiEnumDeviceInterfaces
			(hDevInfo,
			 0,
			 &HidGuid,
			 MemberIndex,
			 &devInfoData);

		if (Result != 0)
		{
			//A device has been detected, so get more information about it.

			/*
			  API function: SetupDiGetDeviceInterfaceDetail
			  Returns: an SP_DEVICE_INTERFACE_DETAIL_DATA structure
			  containing information about a device.
			  To retrieve the information, call this function twice.
			  The first time returns the size of the structure in Length.
			  The second time returns a pointer to the data in DeviceInfoSet.
			  Requires:
			  A DeviceInfoSet returned by SetupDiGetClassDevs
			  The SP_DEVICE_INTERFACE_DATA structure returned by SetupDiEnumDeviceInterfaces.

			  The final parameter is an optional pointer to an SP_DEV_INFO_DATA structure.
			  This application doesn't retrieve or use the structure.
			  If retrieving the structure, set
			  MyDeviceInfoData.cbSize = length of MyDeviceInfoData.
			  and pass the structure's address.
			*/

			//Get the Length value.
			//The call will return with a "buffer too small" error which can be ignored.

			Result = SetupDiGetDeviceInterfaceDetail
				(hDevInfo,
				 &devInfoData,
				 NULL,
				 0,
				 &Length,
				 NULL);

			//Allocate memory for the hDevInfo structure, using the returned Length.

 			detailData = (PSP_DEVICE_INTERFACE_DETAIL_DATA)malloc(Length);

			//Set cbSize in the detailData structure.

			detailData -> cbSize = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA);

			//Call the function again, this time passing it the returned buffer size.

			Result = SetupDiGetDeviceInterfaceDetail
				(hDevInfo,
				 &devInfoData,
				 detailData,
				 Length,
				 &Required,
				 NULL);

			// Open a handle to the device.
			// To enable retrieving information about a system mouse or keyboard,
			// don't request Read or Write access for this handle.

			/*
			  API function: CreateFile
			  Returns: a handle that enables reading and writing to the device.
			  Requires:
			  The DevicePath in the detailData structure
			  returned by SetupDiGetDeviceInterfaceDetail.
			*/

			dev->device._dev =CreateFile
				(detailData->DevicePath,
				 GENERIC_READ | GENERIC_WRITE,
				 FILE_SHARE_READ|FILE_SHARE_WRITE,
				 (LPSECURITY_ATTRIBUTES)NULL,
				 OPEN_EXISTING,
				 0,
				 NULL);

			/*
			  API function: HidD_GetAttributes
			  Requests information from the device.
			  Requires: the handle returned by CreateFile.
			  Returns: a HIDD_ATTRIBUTES structure containing
			  the Vendor ID, Product ID, and Product Version Number.
			  Use this information to decide if the detected device is
			  the one we're looking for.
			*/

			//Set the Size to the number of bytes in the structure.

			Attributes.Size = sizeof(Attributes);

			Result = HidD_GetAttributes
				(dev->device._dev,
				 &Attributes);

			//Is it the desired device?

			MyDeviceDetected = FALSE;

			if ((Attributes.VendorID == VID && Attributes.ProductID == PID))
			{
				if(get_count)
				{
					++device_count;
					CloseHandle(dev->device._dev);
				}
				else
				{
					MyDeviceDetected = TRUE;
					MyDevicePathName = detailData->DevicePath;
					GetDeviceCapabilities(dev->device._dev);
					break;
				}
			}
			else
			{
				CloseHandle(dev->device._dev);
			}
			free(detailData);
		}  //if (Result != 0)

		else
		{
			LastDevice=TRUE;
		}
		//If we haven't found the device yet, and haven't tried every available device,
		//try the next one.
		MemberIndex = MemberIndex + 1;
	}
	while (!LastDevice);
	SetupDiDestroyDeviceInfoList(hDevInfo);
	if(get_count) return device_count;
	if(MyDeviceDetected) return 0;
	return -1;
}

OMRON_DECLSPEC int omron_get_count(omron_device* dev, int VID, int PID)
{
	return omron_open_win32(dev, VID, PID, 0, 1);
}

OMRON_DECLSPEC int omron_open(omron_device* dev, int VID, int PID, unsigned int device_index)
{
	return omron_open_win32(dev, VID, PID, device_index, 0);
}

OMRON_DECLSPEC int omron_close(omron_device* dev)
{
	CloseHandle(dev->device._dev);
	return 0;
}

int omron_set_mode(omron_device* dev, omron_mode mode)
{
	char feature_report[3] = {0x0, (mode & 0xff00) >> 8, (mode & 0x00ff)};
	int ret = HidD_SetFeature(dev->device._dev, feature_report, Capabilities.FeatureReportByteLength);
	if(!ret)
	{
		printf("Cannot send feature! %d\n", GetLastError());
		return (GetLastError() * -1);
	}
	return 0;
}

OMRON_DECLSPEC int omron_read_data(omron_device* dev, unsigned char *input_report)
{
	int Result;
	char read[9];
	Result = ReadFile
		(dev->device._dev,
		 read,
		 Capabilities.InputReportByteLength,
		 &NumberOfBytesRead,
		 NULL);
	memcpy(input_report, read+1, 8);
	return Result;
}

OMRON_DECLSPEC int omron_write_data(omron_device* dev, unsigned char *output_report)
{
	int Result;
	char command[9];
	command[0] = 0x0;
	memcpy((command+1), output_report, 8);
	Result = WriteFile
		(dev->device._dev,
		 command,
		 Capabilities.OutputReportByteLength,
		 &NumberOfBytesRead,
		 (LPOVERLAPPED) &HIDOverlapped);
	return Result;
}

OMRON_DECLSPEC omron_device* omron_create()
{
	omron_device* s = (omron_device*)malloc(sizeof(omron_device));
	s->device._is_open = 0;
	s->device._is_inited = 1;
	return s;
}

OMRON_DECLSPEC void omron_delete(omron_device* dev)
{
	free(dev);
}


text:
package de.fhpotsdam.unfolding.examples.marker.dynamic;

import processing.core.PApplet;

import de.fhpotsdam.unfolding.UnfoldingMap;
import de.fhpotsdam.unfolding.geo.Location;
import de.fhpotsdam.unfolding.marker.Marker;
import de.fhpotsdam.unfolding.marker.MarkerManager;
import de.fhpotsdam.unfolding.marker.SimpleLinesMarker;
import de.fhpotsdam.unfolding.marker.SimplePointMarker;
import de.fhpotsdam.unfolding.utils.MapUtils;

/**
 * Simple example for dynamic marker handling. This adds, removes and clears markers of a single MarkerManager.
 *
 * Press 'r' to remove the Berlin marker, 'a' to re-add it, and 'c' to clear all markers.
 */
@SuppressWarnings("serial")
public class DynamicMarkerApp extends PApplet {

	UnfoldingMap map;

	MarkerManager<Marker> markerManager;
	SimplePointMarker berlinMarker;

	public void setup() {
		size(800, 600, OPENGL);

		map = new UnfoldingMap(this);

		map.zoomToLevel(3);
		map.panTo(new Location(40f, -42f));
		MapUtils.createDefaultEventDispatcher(this, map);

		// Get default MarkerManager (still empty at this moment)
		markerManager = map.getDefaultMarkerManager();

		// Create Markers from Locations
		Location berlinLocation = new Location(52.5f, 13.4f);
		Location mexicoCityLocation = new Location(19.4f, -99.1f);

		// Point Markers
		berlinMarker = new SimplePointMarker(berlinLocation);
		SimplePointMarker mexicoCityMarker = new SimplePointMarker(mexicoCityLocation);
		// Line Marker
		SimpleLinesMarker connectionMarker = new SimpleLinesMarker(berlinLocation, mexicoCityLocation);

		markerManager.addMarker(berlinMarker);
		markerManager.addMarker(mexicoCityMarker);
		markerManager.addMarker(connectionMarker);
	}

	public void draw() {
		background(240);

		// Drawing Markers in handled internally
		map.draw();
	}

	public void keyPressed() {
		if (key == 'r') {
			markerManager.removeMarker(berlinMarker);
		}
		if (key == 'a') {
			markerManager.addMarker(berlinMarker);
		}
		if (key == 'c') {
			markerManager.clearMarkers();
		}
	}

}


text:
package org.springframework.boot.web.servlet.support;

import java.io.IOException;
import java.io.PrintWriter;
import java.util.Collection;
import java.util.Collections;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpServletResponseWrapper;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import org.springframework.boot.web.server.ErrorPage;
import org.springframework.boot.web.server.ErrorPageRegistrar;
import org.springframework.boot.web.server.ErrorPageRegistry;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.util.ClassUtils;
import org.springframework.web.filter.OncePerRequestFilter;
import org.springframework.web.util.NestedServletException;

/**
 * A Servlet {@link Filter} that provides an {@link ErrorPageRegistry} for non-embedded
 * applications (i.e. deployed WAR files). It registers error pages and handles
 * application errors by filtering requests and forwarding to the error pages instead of
 * letting the server handle them. Error pages are a feature of the servlet spec but there
 * is no Java API for registering them in the spec. This filter works around that by
 * accepting error page registrations from Spring Boot's {@link ErrorPageRegistrar} (any
 * beans of that type in the context will be applied to this server).
 *
 * @author Dave Syer
 * @author Phillip Webb
 * @author Andy Wilkinson
 * @since 2.0.0
 */
@Order(Ordered.HIGHEST_PRECEDENCE + 1)
public class ErrorPageFilter implements Filter, ErrorPageRegistry {

	private static final Log logger = LogFactory.getLog(ErrorPageFilter.class);

	// From RequestDispatcher but not referenced to remain compatible with Servlet 2.5

	private static final String ERROR_EXCEPTION = "javax.servlet.error.exception";

	private static final String ERROR_EXCEPTION_TYPE = "javax.servlet.error.exception_type";

	private static final String ERROR_MESSAGE = "javax.servlet.error.message";

	/**
	 * The name of the servlet attribute containing request URI.
	 */
	public static final String ERROR_REQUEST_URI = "javax.servlet.error.request_uri";

	private static final String ERROR_STATUS_CODE = "javax.servlet.error.status_code";

	private static final Set<Class<?>> CLIENT_ABORT_EXCEPTIONS;
	static {
		Set<Class<?>> clientAbortExceptions = new HashSet<>();
		addClassIfPresent(clientAbortExceptions, "org.apache.catalina.connector.ClientAbortException");
		CLIENT_ABORT_EXCEPTIONS = Collections.unmodifiableSet(clientAbortExceptions);
	}

	private String global;

	private final Map<Integer, String> statuses = new HashMap<>();

	private final Map<Class<?>, String> exceptions = new HashMap<>();

	private final OncePerRequestFilter delegate = new OncePerRequestFilter() {

		@Override
		protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
				throws ServletException, IOException {
			ErrorPageFilter.this.doFilter(request, response, chain);
		}

		@Override
		protected boolean shouldNotFilterAsyncDispatch() {
			return false;
		}

	};

	@Override
	public void init(FilterConfig filterConfig) throws ServletException {
		this.delegate.init(filterConfig);
	}

	@Override
	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		this.delegate.doFilter(request, response, chain);
	}

	private void doFilter(HttpServletRequest request, HttpServletResponse response, FilterChain chain)
			throws IOException, ServletException {
		ErrorWrapperResponse wrapped = new ErrorWrapperResponse(response);
		try {
			chain.doFilter(request, wrapped);
			if (wrapped.hasErrorToSend()) {
				handleErrorStatus(request, response, wrapped.getStatus(), wrapped.getMessage());
				response.flushBuffer();
			}
			else if (!request.isAsyncStarted() && !response.isCommitted()) {
				response.flushBuffer();
			}
		}
		catch (Throwable ex) {
			Throwable exceptionToHandle = ex;
			if (ex instanceof NestedServletException) {
				exceptionToHandle = ((NestedServletException) ex).getRootCause();
			}
			handleException(request, response, wrapped, exceptionToHandle);
			response.flushBuffer();
		}
	}

	private void handleErrorStatus(HttpServletRequest request, HttpServletResponse response, int status, String message)
			throws ServletException, IOException {
		if (response.isCommitted()) {
			handleCommittedResponse(request, null);
			return;
		}
		String errorPath = getErrorPath(this.statuses, status);
		if (errorPath == null) {
			response.sendError(status, message);
			return;
		}
		response.setStatus(status);
		setErrorAttributes(request, status, message);
		request.getRequestDispatcher(errorPath).forward(request, response);
	}

	private void handleException(HttpServletRequest request, HttpServletResponse response, ErrorWrapperResponse wrapped,
			Throwable ex) throws IOException, ServletException {
		Class<?> type = ex.getClass();
		String errorPath = getErrorPath(type);
		if (errorPath == null) {
			rethrow(ex);
			return;
		}
		if (response.isCommitted()) {
			handleCommittedResponse(request, ex);
			return;
		}
		forwardToErrorPage(errorPath, request, wrapped, ex);
	}

	private void forwardToErrorPage(String path, HttpServletRequest request, HttpServletResponse response, Throwable ex)
			throws ServletException, IOException {
		if (logger.isErrorEnabled()) {
			String message = "Forwarding to error page from request " + getDescription(request) + " due to exception ["
					+ ex.getMessage() + "]";
			logger.error(message, ex);
		}
		setErrorAttributes(request, 500, ex.getMessage());
		request.setAttribute(ERROR_EXCEPTION, ex);
		request.setAttribute(ERROR_EXCEPTION_TYPE, ex.getClass());
		response.reset();
		response.setStatus(500);
		request.getRequestDispatcher(path).forward(request, response);
		request.removeAttribute(ERROR_EXCEPTION);
		request.removeAttribute(ERROR_EXCEPTION_TYPE);
	}

	/**
	 * Return the description for the given request. By default this method will return a
	 * description based on the request {@code servletPath} and {@code pathInfo}.
	 * @param request the source request
	 * @return the description
	 * @since 1.5.0
	 */
	protected String getDescription(HttpServletRequest request) {
		String pathInfo = (request.getPathInfo() != null) ? request.getPathInfo() : "";
		return "[" + request.getServletPath() + pathInfo + "]";
	}

	private void handleCommittedResponse(HttpServletRequest request, Throwable ex) {
		if (isClientAbortException(ex)) {
			return;
		}
		String message = "Cannot forward to error page for request " + getDescription(request)
				+ " as the response has already been"
				+ " committed. As a result, the response may have the wrong status"
				+ " code. If your application is running on WebSphere Application"
				+ " Server you may be able to resolve this problem by setting"
				+ " com.ibm.ws.webcontainer.invokeFlushAfterService to false";
		if (ex == null) {
			logger.error(message);
		}
		else {
			// User might see the error page without all the data here but throwing the
			// exception isn't going to help anyone (we'll log it to be on the safe side)
			logger.error(message, ex);
		}
	}

	private boolean isClientAbortException(Throwable ex) {
		if (ex == null) {
			return false;
		}
		for (Class<?> candidate : CLIENT_ABORT_EXCEPTIONS) {
			if (candidate.isInstance(ex)) {
				return true;
			}
		}
		return isClientAbortException(ex.getCause());
	}

	private String getErrorPath(Map<Integer, String> map, Integer status) {
		if (map.containsKey(status)) {
			return map.get(status);
		}
		return this.global;
	}

	private String getErrorPath(Class<?> type) {
		while (type != Object.class) {
			String path = this.exceptions.get(type);
			if (path != null) {
				return path;
			}
			type = type.getSuperclass();
		}
		return this.global;
	}

	private void setErrorAttributes(HttpServletRequest request, int status, String message) {
		request.setAttribute(ERROR_STATUS_CODE, status);
		request.setAttribute(ERROR_MESSAGE, message);
		request.setAttribute(ERROR_REQUEST_URI, request.getRequestURI());
	}

	private void rethrow(Throwable ex) throws IOException, ServletException {
		if (ex instanceof RuntimeException) {
			throw (RuntimeException) ex;
		}
		if (ex instanceof Error) {
			throw (Error) ex;
		}
		if (ex instanceof IOException) {
			throw (IOException) ex;
		}
		if (ex instanceof ServletException) {
			throw (ServletException) ex;
		}
		throw new IllegalStateException(ex);
	}

	@Override
	public void addErrorPages(ErrorPage... errorPages) {
		for (ErrorPage errorPage : errorPages) {
			if (errorPage.isGlobal()) {
				this.global = errorPage.getPath();
			}
			else if (errorPage.getStatus() != null) {
				this.statuses.put(errorPage.getStatus().value(), errorPage.getPath());
			}
			else {
				this.exceptions.put(errorPage.getException(), errorPage.getPath());
			}
		}
	}

	@Override
	public void destroy() {
	}

	private static void addClassIfPresent(Collection<Class<?>> collection, String className) {
		try {
			collection.add(ClassUtils.forName(className, null));
		}
		catch (Throwable ex) {
		}
	}

	private static class ErrorWrapperResponse extends HttpServletResponseWrapper {

		private int status;

		private String message;

		private boolean hasErrorToSend = false;

		ErrorWrapperResponse(HttpServletResponse response) {
			super(response);
		}

		@Override
		public void sendError(int status) throws IOException {
			sendError(status, null);
		}

		@Override
		public void sendError(int status, String message) throws IOException {
			this.status = status;
			this.message = message;
			this.hasErrorToSend = true;
			// Do not call super because the container may prevent us from handling the
			// error ourselves
		}

		@Override
		public int getStatus() {
			if (this.hasErrorToSend) {
				return this.status;
			}
			// If there was no error we need to trust the wrapped response
			return super.getStatus();
		}

		@Override
		public void flushBuffer() throws IOException {
			sendErrorIfNecessary();
			super.flushBuffer();
		}

		private void sendErrorIfNecessary() throws IOException {
			if (this.hasErrorToSend && !isCommitted()) {
				((HttpServletResponse) getResponse()).sendError(this.status, this.message);
			}
		}

		String getMessage() {
			return this.message;
		}

		boolean hasErrorToSend() {
			return this.hasErrorToSend;
		}

		@Override
		public PrintWriter getWriter() throws IOException {
			sendErrorIfNecessary();
			return super.getWriter();
		}

		@Override
		public ServletOutputStream getOutputStream() throws IOException {
			sendErrorIfNecessary();
			return super.getOutputStream();
		}

	}

}


text:
namespace Appccelerate.Bootstrapper.Configuration
{
    using System.Collections.Generic;

    using FluentAssertions;

    using Xunit;

    public class ExtensionConfigurationSectionHelperTest
    {
        [Fact]
        public void CreateSection_MustBuildUpCorrectConfigurationSection()
        {
            var section = ExtensionConfigurationSectionHelper.CreateSection(new Dictionary<string, string> { { "A", "B" }, { "C", "D" }, });

            section.Configuration["A"].Value.Should().Be("B");
            section.Configuration["C"].Value.Should().Be("D");
        }

        [Fact]
        public void CreateSection_WithParams_MustBuildUpCorrectConfigurationSection()
        {
            var section = ExtensionConfigurationSectionHelper.CreateSection(new KeyValuePair<string, string>("A", "B"));

            section.Configuration["A"].Value.Should().Be("B");
        }
    }
}


text:
using System;
using System.Threading.Tasks;
using Microsoft.AspNetCore.Builder;
using Microsoft.AspNetCore.Http;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Hosting;

namespace Cuemon.Extensions.Xunit.Hosting.AspNetCore.Mvc
{
    /// <summary>
    /// Provides a set of static methods for ASP.NET Core MVC filter unit testing.
    /// </summary>
    public static class MvcFilterTestFactory
    {
        /// <summary>
        /// Creates and returns an <see cref="IMvcFilterTest"/> implementation.
        /// </summary>
        /// <param name="pipelineSetup">The <see cref="IApplicationBuilder"/> which may be configured.</param>
        /// <param name="serviceSetup">The <see cref="IServiceCollection"/> which may be configured.</param>
        /// <param name="hostSetup">The <see cref="IHostBuilder"/> which may be configured.</param>
        /// <returns>An instance of an <see cref="IMvcFilterTest"/> implementation.</returns>
        public static IMvcFilterTest CreateMvcFilterTest(Action<IApplicationBuilder> pipelineSetup = null, Action<IServiceCollection> serviceSetup = null, Action<IHostBuilder> hostSetup = null)
        {
            return new MvcFilterAspNetCoreHostTest(pipelineSetup, serviceSetup, hostSetup);
        }

        /// <summary>
        /// Creates and returns an <see cref="IMvcFilterTest"/> implementation.
        /// </summary>
        /// <param name="pipelineSetup">The <see cref="IApplicationBuilder"/> which may be configured.</param>
        /// <param name="serviceSetup">The <see cref="IServiceCollection"/> which may be configured.</param>
        /// <param name="hostSetup">The <see cref="IHostBuilder"/> which may be configured.</param>
        /// <returns>An instance of an <see cref="IMvcFilterTest"/> implementation.</returns>
        public static IMvcFilterTest CreateMvcFilterTest(Action<HostBuilderContext, IApplicationBuilder> pipelineSetup = null, Action<HostBuilderContext, IServiceCollection> serviceSetup = null, Action<IHostBuilder> hostSetup = null)
        {
            return new MvcFilterAspNetCoreHostTest(pipelineSetup, serviceSetup, hostSetup);
        }

        /// <summary>
        /// Runs a filter/middleware test.
        /// </summary>
        /// <param name="pipelineSetup">The <see cref="IApplicationBuilder" /> which may be configured.</param>
        /// <param name="serviceSetup">The <see cref="IServiceCollection" /> which may be configured.</param>
        /// <param name="hostSetup">The <see cref="IHostBuilder" /> which may be configured.</param>
        /// <returns>A task that represents the execution of the middleware.</returns>
        public static async Task RunMvcFilterTest(Action<IApplicationBuilder> pipelineSetup = null, Action<IServiceCollection> serviceSetup = null, Action<IHostBuilder> hostSetup = null)
        {
            using (var middleware = CreateMvcFilterTest(pipelineSetup, serviceSetup, hostSetup))
            {
                var context = middleware.ServiceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
                var pipeline = middleware.Application.Build();
                await pipeline(context).ConfigureAwait(false);
            }
        }

        /// <summary>
        /// Runs a filter/middleware test.
        /// </summary>
        /// <param name="pipelineSetup">The <see cref="IApplicationBuilder" /> which may be configured.</param>
        /// <param name="serviceSetup">The <see cref="IServiceCollection" /> which may be configured.</param>
        /// <param name="hostSetup">The <see cref="IHostBuilder" /> which may be configured.</param>
        /// <returns>A task that represents the execution of the middleware.</returns>
        public static async Task RunMvcFilterTest(Action<HostBuilderContext, IApplicationBuilder> pipelineSetup = null, Action<HostBuilderContext, IServiceCollection> serviceSetup = null, Action<IHostBuilder> hostSetup = null)
        {
            using (var middleware = CreateMvcFilterTest(pipelineSetup, serviceSetup, hostSetup))
            {
                var context = middleware.ServiceProvider.GetRequiredService<IHttpContextAccessor>().HttpContext;
                var pipeline = middleware.Application.Build();
                await pipeline(context).ConfigureAwait(false);
            }
        }
    }
}


text:
package org.iguanatool.inputgeneration.objectivefunction.condition;

import org.iguanatool.inputgeneration.objectivefunction.InputGenerationObjectiveValue;
import org.iguanatool.testobject.structure.condition.Condition;
import org.iguanatool.testobject.trace.condition.TraceCondition;

import java.util.List;

/**
 * User: phil
 * Date: 13-Jun-2006
 * Time: 15:35:00
 */
public abstract class ConditionObjectiveFunction {

    protected InputGenerationObjectiveValue trueOutcome;
    protected InputGenerationObjectiveValue falseOutcome;

    public abstract void compute(Condition condition,
                                 List<TraceCondition> traceConditions);

    public InputGenerationObjectiveValue getTrueOutcome() {
        return trueOutcome;
    }

    public InputGenerationObjectiveValue getFalseOutcome() {
        return falseOutcome;
    }

    public InputGenerationObjectiveValue getOutcome(boolean outcome) {
        if (outcome) {
            return trueOutcome;
        } else {
            return falseOutcome;
        }
    }
}


text:
**`eegDb`** is an eeglab plugin that eases up managing preprocessing routines. It allows to create project databases for reproducible eeg preprocessing with eeglab.

:construction:
The project is currently under construction, the [documentation](http://eegdb.readthedocs.io/en/latest/) is not complete.
:construction:

### Installation
[See the installation instructions](http://eegdb.readthedocs.io/en/latest/Installation/)

### Creating database
[see here](http://eegdb.readthedocs.io/en/latest/creating%20database/)


text:
from __future__ import absolute_import

from . import option_list
import digits.device_query

option_list['gpu_list'] = ','.join([str(x) for x in xrange(len(digits.device_query.get_devices()))])


text: Simple library for *Super Chip* interpreters.


text:
Delete all lines containing a pattern in VIM
===

The ***ex*** command `g` is very useful for acting on lines that match a
pattern. We can use it with the `d` command, to delete all the lines that
contain a particular pattern, or all the lines that do not contain a pattern.

To delete all lines containing a pattern - say *profile* we do this -
```bash
:g/profile/d
```
---

Deleting all lines containing that are empty or contain only whitespace
```bash
:g/^\s*$/d
```
>**NOTE:** `\s` stands for whitespace character, `^` and `&` are anchors which mean
*beginning* and *end of line* respectively.

---

To delete all the lines that do **NOT** contain a pattern, use `g!` instead
of `g`
```bash
:g!/^\s*"/d  #(Lines that are not starting with a ")
```

We can also use `v` instead of `g!` to match lines **NOT** containing a
pattern.


text:
@interface ViewController ()

@property (weak, nonatomic) IBOutlet UIQuickSilver *quickSilver;
@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.quickSilver.animate = YES;
    self.quickSilver.current = 20;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

@end


text:
Notable changes
===============

Updated RPCs
------------

- `upgradewallet` will now automatically flush the keypool if upgrading
from a non-HD wallet to an HD wallet, to immediately start using the
newly-generated HD keys.
- a new RPC `newkeypool` has been added, which will flush (entirely
clear and refill) the keypool.


text:
<?php

/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */

namespace Entitys;

/**
 * Description of EntityUserType
 *
 * @author danielvelasquez
 */
class EntityUserType {

    //put your code here
    private $id_tipo_usuario;
    private $tipo_usuario;

    function __construct($data) {
        $this->id_tipo_usuario = $data['ID_TIPO_USUARIO'];
        $this->tipo_usuario = $data['TIPO_USUARIO'];
    }

    function getId_tipo_usuario() {
        return $this->id_tipo_usuario;
    }

    function getTipo_usuario() {
        return $this->tipo_usuario;
    }

    function setId_tipo_usuario($id_tipo_usuario) {
        $this->id_tipo_usuario = $id_tipo_usuario;
    }

    function setTipo_usuario($tipo_usuario) {
        $this->tipo_usuario = $tipo_usuario;
    }

}


text:
package org.mapfish.print.processor.map;

import org.apache.batik.transcoder.TranscoderException;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import org.junit.Test;
import org.mapfish.print.AbstractMapfishSpringTest;
import org.mapfish.print.TestHttpClientFactory;
import org.mapfish.print.attribute.map.AreaOfInterest;
import org.mapfish.print.config.Configuration;
import org.mapfish.print.config.ConfigurationFactory;
import org.mapfish.print.config.Template;
import org.mapfish.print.output.Values;
import org.mapfish.print.test.util.ImageSimilarity;
import org.mapfish.print.wrapper.json.PJsonObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.annotation.DirtiesContext;

import java.io.File;
import java.io.IOException;
import java.net.URI;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ForkJoinPool;
import java.util.concurrent.ForkJoinTask;
import java.util.function.Function;
import javax.annotation.Nonnull;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mapfish.print.attribute.map.AreaOfInterest.AoiDisplay.CLIP;
import static org.mapfish.print.attribute.map.AreaOfInterest.AoiDisplay.RENDER;

/**
 * Basic test of the Map processor.
 *
 * Created by Jesse on 3/26/14.
 */
public class CreateMapProcessorAoiTest extends AbstractMapfishSpringTest {
    public static final String BASE_DIR = "center_wms1_0_0_flexiblescale_area_of_interest/";

    @Autowired
    private ConfigurationFactory configurationFactory;
    @Autowired
    private TestHttpClientFactory requestFactory;
    @Autowired
    private ForkJoinPool forkJoinPool;

    private static PJsonObject loadJsonRequestData() throws IOException {
        return parseJSONObjectFromFile(CreateMapProcessorAoiTest.class, BASE_DIR + "requestData.json");
    }

    @Test
    @DirtiesContext
    public void testExecute() throws Exception {
        final String host = "center_wms1_0_0_flexiblescale";
        requestFactory.registerHandler(
                input -> (("" + input.getHost()).contains(host + ".wms")) ||
                        input.getAuthority().contains(host + ".wms"),
                createFileHandler("/map-data/zoomed-in-ny-tiger.tif")
        );
        requestFactory.registerHandler(
                input -> (("" + input.getHost()).contains(host + ".json")) ||
                        input.getAuthority().contains(host + ".json"),
                createFileHandler(uri -> "/map-data" + uri.getPath())
        );
        final Configuration config = configurationFactory.getConfig(getFile(BASE_DIR + "config.yaml"));
        final Template template = config.getTemplate("main");

        createMap(template, "expectedSimpleImage-default-transparent.png",
                  RENDER, null, false, null, 45);
        /* jpeg */
        createMap(template, "expectedSimpleImage-default.png",
                  RENDER, null, false, true, null, 50);
        createMap(template, "expectedSimpleImage-render-thinline-transparent.png",
                  RENDER, "file://thinline.sld", false, null, 45);
        /* jpeg */
        createMap(template, "expectedSimpleImage-render-thinline.png",
                  RENDER, "file://thinline.sld", false, true, null, 50);
        createMap(template, "expectedSimpleImage-render-jsonStyle.png",
                  RENDER, createJsonStyle().toString(), false, null, 45);
        createMap(template, "expectedSimpleImage-render-polygon.png",
                  RENDER, "polygon", false, null, 45);
        createMap(template, "expectedSimpleImage-none-transparent.png",
                  AreaOfInterest.AoiDisplay.NONE, null, false, null, 45);
        /* jpeg */
        createMap(template, "expectedSimpleImage-none.png",
                  AreaOfInterest.AoiDisplay.NONE, null, false, true, null, 50);
        createMap(template, "expectedSimpleImage-clip-transparent.png",
                  CLIP, null, false, null, 10);
        /* jpeg */
        createMap(template, "expectedSimpleImage-clip.png",
                  CLIP, null, false, true, null, 10);

        // Test when SVG is used for vector layers
        createMap(template, "expectedSimpleImage-render-polygon-svg-transparent.png",
                  RENDER, createJsonStyle().toString(), true, null, 45);
        /* jpeg */
        createMap(template, "expectedSimpleImage-render-polygon-svg.png",
                  RENDER, createJsonStyle().toString(), true, true, null, 50);
        createMap(template, "expectedSimpleImage-clip-svg-transparent.png",
                  CLIP, null, true, null, 5);
        /* jpeg */
        createMap(template, "expectedSimpleImage-clip-svg.png",
                  CLIP, null, true, true, null, 10);
        Function<PJsonObject, Void> setRotationUpdater = (@Nonnull PJsonObject input) -> {
            try {
                getMapAttributes(input).getInternalObj().put("rotation", 90);
            } catch (JSONException e) {
                throw new RuntimeException(e);
            }
            return null;
        };
        createMap(template, "expectedSimpleImage-rotate-clip-svg.png",
                  CLIP, null, true, setRotationUpdater, 10);
        createMap(template, "expectedSimpleImage-rotate-render-svg.png",
                  RENDER, null, true, setRotationUpdater, 75);
    }

    private JSONObject createJsonStyle() throws JSONException {
        JSONObject jsonStyle = new JSONObject();
        jsonStyle.put("version", "2");
        final JSONObject polygonSymb = new JSONObject();
        polygonSymb.put("type", "polygon");
        polygonSymb.put("fillColor", "green");
        polygonSymb.put("fillOpacity", ".8");
        polygonSymb.put("strokeColor", "black");
        JSONArray symbs = new JSONArray();
        symbs.put(polygonSymb);

        JSONObject rule = new JSONObject();
        rule.put("symbolizers", symbs);
        jsonStyle.put("*", rule);
        return jsonStyle;
    }

    private void createMap(
            Template template, String expectedImageName, AreaOfInterest.AoiDisplay aoiDisplay,
            String styleRef, boolean useSVG, Function<PJsonObject, Void> requestUpdater, double tolerance)
            throws IOException, JSONException, TranscoderException, ExecutionException, InterruptedException {
        createMap(template, expectedImageName, aoiDisplay, styleRef, useSVG, false,
                  requestUpdater, tolerance);
    }

    private void createMap(
            Template template, String expectedImageName, AreaOfInterest.AoiDisplay
            aoiDisplay, String styleRef, boolean useSVG, boolean useJPEG,
            Function<PJsonObject, Void> requestUpdater, double tolerance) throws IOException,
            JSONException, TranscoderException,
            ExecutionException,
            InterruptedException {
        PJsonObject requestData = loadJsonRequestData();
        final PJsonObject mapAttribute = getMapAttributes(requestData);
        mapAttribute.getJSONArray("layers").getJSONObject(0).getInternalObj().put("renderAsSvg", useSVG);
        if (useJPEG) {
            mapAttribute.getJSONArray("layers").getJSONObject(1).getInternalObj().put("imageFormat", "jpeg");
        }

        final PJsonObject areaOfInterest = mapAttribute.getJSONObject("areaOfInterest");
        // doesn't have to be lowercase, this is to make things more interesting
        areaOfInterest.getInternalObj().put("display", aoiDisplay.name().toLowerCase());
        areaOfInterest.getInternalObj().put("style", styleRef);

        if (requestUpdater != null) {
            requestUpdater.apply(requestData);
        }

        Values values = new Values("test", requestData, template, getTaskDirectory(),
                                   this.requestFactory, new File("."));

        final ForkJoinTask<Values> taskFuture = this.forkJoinPool.submit(
                template.getProcessorGraph().createTask(values));
        taskFuture.get();

        @SuppressWarnings("unchecked")
        List<URI> layerGraphics = (List<URI>) values.getObject("layerGraphics", List.class);
        int expectedNumberOfLayers = useSVG ? (aoiDisplay == RENDER ? 3 : 2) : (useJPEG ? 2 : 1);
        assertEquals(expectedNumberOfLayers, layerGraphics.size());
        if (useJPEG) {
            assertTrue(layerGraphics.get(0).getPath().endsWith(".jpeg"));
        }

        new ImageSimilarity(getFile(BASE_DIR + "/output/" + expectedImageName))
                .assertSimilarity(layerGraphics, 630, 294, tolerance);
    }

    private PJsonObject getMapAttributes(PJsonObject requestData) {
        return requestData.getJSONObject("attributes").getJSONObject("map");
    }
}


text:
extern CAppModule _Module;

LRESULT CTabButtonAdd::OnPaint( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	PAINTSTRUCT paintStruct;
	::BeginPaint(m_hWnd, &paintStruct);

	RECT rc;
	GetClientRect(&rc);
	Gdiplus::Bitmap bitmap(rc.right, rc.bottom);
	Gdiplus::Graphics *mg = Gdiplus::Graphics::FromImage(&bitmap);
	Gdiplus::SolidBrush bkBrush(Gdiplus::Color(255,255,255,255));
	mg->FillRectangle(&bkBrush, rc.left, rc.top, rc.right-rc.left, rc.bottom-rc.top);
	mg->DrawImage(m_pCurrentImage,0,0,m_pCurrentImage->GetWidth(),m_pCurrentImage->GetHeight());

	Gdiplus::Graphics g(paintStruct.hdc);
	g.DrawImage(&bitmap,rc.left, rc.top, rc.right-rc.left ,rc.bottom-rc.top);

	::EndPaint(m_hWnd, &paintStruct);
	return 0;
}

CTabButtonAdd::CTabButtonAdd()
:m_hParentWindow(NULL)
,m_bMouseTrack(TRUE)
,m_pNormalImage(NULL)
,m_pHoverImage(NULL)
,m_pCurrentImage(NULL)
{

}

CTabButtonAdd::~CTabButtonAdd()
{
	if (m_pNormalImage){
		delete m_pNormalImage;
		m_pNormalImage = NULL;
	}
	if (m_pHoverImage){
		delete m_pHoverImage;
		m_pHoverImage = NULL;
	}
	m_pCurrentImage = NULL;

	if (IsWindow()){
		DestroyWindow();
		m_hWnd = NULL;
	}
}

void CTabButtonAdd::SetParentHWND( HWND hParent )
{
	m_hParentWindow = hParent;
}

LRESULT CTabButtonAdd::OnCreate( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	ImageFromIDResource(_Module.m_hInstResource, IDR_TAB_BUTTON_ADD, L"PNG", m_pNormalImage);
	ImageFromIDResource(_Module.m_hInstResource, IDR_TAB_BUTTON_ADD_OVER, L"PNG", m_pHoverImage);
	m_pCurrentImage = m_pNormalImage;
	return 0;
}

LRESULT CTabButtonAdd::OnLButtonUp( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	::PostMessage(m_hParentWindow, WM_CLICK_ADD_TAB, (WPARAM)m_hWnd, 0);
	return 0;
}

LRESULT CTabButtonAdd::OnMouseHover( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	m_pCurrentImage = m_pHoverImage;
	RedrawWindow();
	return 0;
}

LRESULT CTabButtonAdd::OnMouseLeave( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	m_pCurrentImage = m_pHoverImage;
	RedrawWindow();
	m_bMouseTrack = TRUE;
	return 0;
}

LRESULT CTabButtonAdd::OnMouseMove( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	if (m_bMouseTrack)
	{
		TRACKMOUSEEVENT csTME;
		csTME.cbSize = sizeof(csTME);
		csTME.dwFlags = TME_LEAVE|TME_HOVER;
		csTME.hwndTrack = m_hWnd;
		csTME.dwHoverTime = 10;
		::_TrackMouseEvent(&csTME);
		m_bMouseTrack=FALSE;
	}
	return 0;
}

LRESULT CTabButtonAdd::OnEraseBKGnd( UINT uMsg, WPARAM wParam, LPARAM lParam, BOOL& bHandled )
{
	return 0;
}


text:
from django.http import HttpResponseForbidden #, HttpResponseRedirect, Http404
# from django.shortcuts import render_to_response
from django.template import loader, RequestContext
# from django.utils.translation import ugettext, ugettext_lazy as _

# modified from django-authority
def permission_denied(request, template_name=None, extra_context={}):
    """
    Default 403 handler.

    Templates: `403.html`
    Context:
        request_path
            The path of the requested URL (e.g., '/app/pages/bad_page/')
    """
    if template_name is None:
        template_name = ('403.html',)
    context = {
        'request_path': request.path,
    }
    context.update(extra_context)
    return HttpResponseForbidden(loader.render_to_string(template_name, context,
                                 context_instance=RequestContext(request)))


text:
<?php

namespace FKakSila\Bundle\MainBundle\DataFixtures\ORM;

use Doctrine\Common\DataFixtures\FixtureInterface;
use Doctrine\Common\Persistence\ObjectManager;
use FKakSila\Bundle\MainBundle\Entity\Letter;

class LoadLetter implements FixtureInterface
{
    /**
     * {@inheritDoc}
     */
    public function load(ObjectManager $manager)
    {
        $openFile = fopen(__DIR__ . "/f_kak_sila.csv", "r");
        while (($data = fgetcsv($openFile, 1000, ",")) !== FALSE) {
            $letter = new Letter();
            $letter->setName(trim($data[0]));
            $letter->setTranscription(trim($data[1]));
            $letter->setDescription(trim($data[2]));

            $manager->persist($letter);
        }
        $manager->flush();
        fclose($openFile);
    }
}


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="PowerWebView">
        <attr name="allow_content_access" format="boolean" />
        <attr name="allow_file_access" format="boolean" />
        <attr name="allow_file_access_from_file_urls" format="boolean" />
        <attr name="allow_universal_access_from_file_urls" format="boolean" />
        <attr name="app_cache_enabled" format="boolean" />
        <attr name="block_network_image" format="boolean" />
        <attr name="block_network_loads" format="boolean" />
        <attr name="geolocation_enabled" format="boolean" />
        <attr name="java_script_can_open_windows_automatically" format="boolean" />
        <attr name="loads_images_automatically" format="boolean" />
        <attr name="media_playback_requires_user_gesture" format="boolean" />
        <attr name="support_multiple_windows" format="boolean" />

        <attr name="java_script_enabled" format="boolean" />
        <attr name="dom_storage_enabled" format="boolean" />
        <attr name="database_enabled" format="boolean" />
        <attr name="save_form_data" format="boolean" />
        <attr name="cache_mode">
            <enum name="load_default" value="-1" />
            <enum name="load_cache_else_network" value="1" />
            <enum name="load_no_cache" value="2" />
            <enum name="load_cached_only" value="3" />
        </attr>
        <attr name="need_initial_focus" format="boolean" />
        <attr name="built_in_zoom_controls" format="boolean" />
        <attr name="display_zoom_controls" format="boolean" />
        <attr name="support_zoom" format="boolean" />
        <attr name="use_wide_view_port" format="boolean" />
        <attr name="load_with_overview_mode" format="boolean" />
    </declare-styleable>
</resources>


text:
class MyFirstCairoPlugin : public IPlug
{
public:
  MyFirstCairoPlugin(IPlugInstanceInfo instanceInfo);
  ~MyFirstCairoPlugin();

  void Reset();
  void OnParamChange(int paramIdx);
  void ProcessDoubleReplacing(double** inputs, double** outputs, int nFrames);

private:
  double mGain;
};

#endif


text:
'use strict';

var chai = require('chai');
var assert = chai.assert;

/* global -Promise */
var Promise = require('bluebird');
var _ = require('underscore');
var path = require('path');
var util = require('../../lib/util.js');

describe('util.js', function () {
  describe('getFileList', function () {
    it('should throw an exception when passed an invalid object');

    it('should return a promise when given a string or an Array', function () {
      var promise = util.getFileList(__dirname + '/../fixtures/btoa.js');
      assert(promise instanceof Promise);
    });

    it('should use resolve an array with a single file when passed a filename as a string',
       function (done) {
         util.getFileList(__dirname + '/../fixtures/window/btoa.js')
           .then(function (files) {
             assert(_.isArray(files));
             assert.equal(files.length, 1);
             assert.equal(files[0], path.resolve(__dirname + '/../fixtures/window/btoa.js'));
             done();
           });
       });

    it('should use resolve an array with a single file when passed a filename as an array',
      function (done) {
        util.getFileList([__dirname + '/../fixtures/window/btoa.js'])
          .then(function (files) {
            assert(_.isArray(files));
            assert.equal(files.length, 1);
            assert.equal(files[0], path.resolve(__dirname + '/../fixtures/window/btoa.js'));
            done();
          });
      });

    it('should use minimatch to resolve to an array of files when passed an array of paths ' +
      'containing stars', function (done) {
        util.getFileList([__dirname + '/../fixtures/**/*.js'])
          .then(function (files) {
            assert(_.isArray(files));
            assert.equal(files.length, 8);
            assert(_.contains(files, path.resolve(__dirname + '/../fixtures/window/btoa.js')));
            done();
          });
      });

    it('should use minimatch to resolve to an array of files when passed a string of paths ' +
      'containing stars', function (done) {
        util.getFileList(__dirname + '/../fixtures/**/*.js')
          .then(function (files) {
            assert(_.isArray(files));
            assert.equal(files.length, 8);
            assert(_.contains(files, path.resolve(__dirname + '/../fixtures/window/btoa.js')));
            done();
          });
      });
  });
});


text:
package org.apache.flink.runtime.highavailability.nonha.embedded;

import org.apache.flink.api.common.JobID;

import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Executor;

/**
 * {@link EmbeddedHaServices} extension for testing purposes.
 */
public class TestingEmbeddedHaServices extends EmbeddedHaServices {

	public TestingEmbeddedHaServices(Executor executor) {
		super(executor);
	}

	public CompletableFuture<Void> revokeDispatcherLeadership() {
		final EmbeddedLeaderService dispatcherLeaderService = getDispatcherLeaderService();
		return dispatcherLeaderService.revokeLeadership();
	}

	public CompletableFuture<Void> grantDispatcherLeadership() {
		final EmbeddedLeaderService dispatcherLeaderService = getDispatcherLeaderService();
		return dispatcherLeaderService.grantLeadership();
	}

	public CompletableFuture<Void> revokeJobMasterLeadership(JobID jobId) {
		final EmbeddedLeaderService jobMasterLeaderService = getJobManagerLeaderService(jobId);
		return jobMasterLeaderService.revokeLeadership();
	}

	public CompletableFuture<Void> grantJobMasterLeadership(JobID jobId) {
		final EmbeddedLeaderService jobMasterLeaderService = getJobManagerLeaderService(jobId);
		return jobMasterLeaderService.grantLeadership();
	}

	public CompletableFuture<Void> revokeResourceManagerLeadership() {
		final EmbeddedLeaderService resourceManagerLeaderService = getResourceManagerLeaderService();
		return resourceManagerLeaderService.revokeLeadership();
	}

	public CompletableFuture<Void> grantResourceManagerLeadership() {
		final EmbeddedLeaderService resourceManagerLeaderService = getResourceManagerLeaderService();
		return resourceManagerLeaderService.grantLeadership();
	}
}


text:
import numpy as np
from gridworld import GridWorld

def print_policy(policy_matrix):
    '''Print the policy using specific symbol.

    * terminal state
    ^ > v < up, right, down, left
    # obstacle
    '''
    counter = 0
    shape = policy_matrix.shape
    policy_string = ""
    for row in range(shape[0]):
        for col in range(shape[1]):
            if(policy_matrix[row,col] == -1): policy_string += " *  "
            elif(policy_matrix[row,col] == 0): policy_string += " ^  "
            elif(policy_matrix[row,col] == 1): policy_string += " >  "
            elif(policy_matrix[row,col] == 2): policy_string += " v  "
            elif(policy_matrix[row,col] == 3): policy_string += " <  "
            elif(np.isnan(policy_matrix[row,col])): policy_string += " #  "
            counter += 1
        policy_string += '\n'
    print(policy_string)

def get_return(state_list, gamma):
    '''Get the return for a list of action-state values.

    @return get the Return
    '''
    counter = 0
    return_value = 0
    for visit in state_list:
        reward = visit[2]
        return_value += reward * np.power(gamma, counter)
        counter += 1
    return return_value

def update_policy(episode_list, policy_matrix, state_action_matrix):
    '''Update a policy making it greedy in respect of the state-action matrix.

    @return the updated policy
    '''
    for visit in episode_list:
        observation = visit[0]
        col = observation[1] + (observation[0]*4)
        if(policy_matrix[observation[0], observation[1]] != -1):
            policy_matrix[observation[0], observation[1]] = \
                np.argmax(state_action_matrix[:,col])
    return policy_matrix

def main():

    env = GridWorld(3, 4)

    #Define the state matrix
    state_matrix = np.zeros((3,4))
    state_matrix[0, 3] = 1
    state_matrix[1, 3] = 1
    state_matrix[1, 1] = -1
    print("State Matrix:")
    print(state_matrix)

    #Define the reward matrix
    reward_matrix = np.full((3,4), -0.04)
    reward_matrix[0, 3] = 1
    reward_matrix[1, 3] = -1
    print("Reward Matrix:")
    print(reward_matrix)

    #Define the transition matrix
    transition_matrix = np.array([[0.8, 0.1, 0.0, 0.1],
                                  [0.1, 0.8, 0.1, 0.0],
                                  [0.0, 0.1, 0.8, 0.1],
                                  [0.1, 0.0, 0.1, 0.8]])

    #Random policy
    policy_matrix = np.random.randint(low=0, high=4, size=(3, 4)).astype(np.float32)
    policy_matrix[1,1] = np.NaN #NaN for the obstacle at (1,1)
    policy_matrix[0,3] = policy_matrix[1,3] = -1 #No action for the terminal states

    #Set the matrices in the world
    env.setStateMatrix(state_matrix)
    env.setRewardMatrix(reward_matrix)
    env.setTransitionMatrix(transition_matrix)

    state_action_matrix = np.random.random_sample((4,12)) # Q
    #init with 1.0e-10 to avoid division by zero
    running_mean_matrix = np.full((4,12), 1.0e-10)
    gamma = 0.999
    tot_epoch = 500000
    print_epoch = 3000

    for epoch in range(tot_epoch):
        #Starting a new episode
        episode_list = list()
        #Reset and return the first observation and reward
        observation = env.reset(exploring_starts=True)
        #action = np.random.choice(4, 1)
        #action = policy_matrix[observation[0], observation[1]]
        #episode_list.append((observation, action, reward))
        is_starting = True
        for _ in range(1000):
            #Take the action from the action matrix
            action = policy_matrix[observation[0], observation[1]]
            #If the episode just started then it is
                #necessary to choose a random action (exploring starts)
            if(is_starting):
                action = np.random.randint(0, 4)
                is_starting = False
            #Move one step in the environment and get obs and reward
            new_observation, reward, done = env.step(action)
            #Append the visit in the episode list
            episode_list.append((observation, action, reward))
            observation = new_observation
            if done: break
        #The episode is finished, now estimating the utilities
        counter = 0
        #Checkup to identify if it is the first visit to a state
        checkup_matrix = np.zeros((4,12))
        #This cycle is the implementation of First-Visit MC.
        #For each state stored in the episode list check if it
        #is the rist visit and then estimate the return.
        for visit in episode_list:
            observation = visit[0]
            action = visit[1]
            col = int(observation[1] + (observation[0]*4))
            row = int(action)
            if(checkup_matrix[row, col] == 0):
                return_value = get_return(episode_list[counter:], gamma)
                running_mean_matrix[row, col] += 1
                state_action_matrix[row, col] += return_value
                checkup_matrix[row, col] = 1
            counter += 1
        #Policy Update
        policy_matrix = update_policy(episode_list,
                                      policy_matrix,
                                      state_action_matrix/running_mean_matrix)
        #Printing
        if(epoch % print_epoch == 0):
            print("")
            print("State-Action matrix after " + str(epoch+1) + " iterations:")
            print(state_action_matrix / running_mean_matrix)
            print("Policy matrix after " + str(epoch+1) + " iterations:")
            print(policy_matrix)
            print_policy(policy_matrix)
    #Time to check the utility matrix obtained
    print("Utility matrix after " + str(tot_epoch) + " iterations:")
    print(state_action_matrix / running_mean_matrix)

if __name__ == "__main__":
    main()


text:
/* File Description
 * Original Works/Author: Thomas Slusny
 * Other Contributors: Marshall Ward
 * Author Website: http://indiearmory.com
 * License: MIT
*/

using System;
using System.Collections.Generic;
using System.IO;
using System.Reflection;
using System.Xml.Linq;

using SFML.Graphics;
using SFML.Window;
using CookieLib.Tiled;

namespace CookieLib.Tiled.Renderer
{
	// Canvas tracks three coordinate systems:
	// 1. pWidth/Height: Canvas pixel count
	// 2. tWidth/Height: Canvas tile count
	public class TmxCanvas
	{
		// User-defined (or derived) fields
		public int tMaxWidth = 29;
		public int tMaxHeight = 19;

		// Canvas size
		public int pWidth;          // Canvas pixel width
		public int pHeight;         // Canvas pixel height
		public float tileScale;     // Canvas-to-window scale

		public int tWidth;      // # of (full) tiles per width
		public int tHeight;     // # of (full) tiles per height
		public int tHalo = 2;   // # of rendered tiles outside viewport

		// Camera position (focal tile)
		public int pX;      // Camera X position in pixels
		public int pY;      // Camera Y position in pixels
		public int tX;      // Tile.X containing camera
		public int tY;      // Tile.Y containing camera

		// Canvas loop hoisting
		public int tStartX;
		public int tEndX;
		public int tStartY;
		public int tEndY;

		// Mosaic parameters
		// (Note: Testing with default arguments)
		public int pTileWidth = 32;      // Tile width in pixels
		public int pTileHeight = 32;     // Tile height in pixels

		// Necessary?
		public RenderTarget game;
		public Vector2f camera;
		public Vector2f origin;

		public TmxCanvas(RenderTarget gameInput, Vector2i maxsize, Vector2i tileSize)
		{
			game = gameInput;

			pTileWidth = tileSize.X;
			pTileHeight = tileSize.Y;

			// Get centre pixel (or left/above centre)
			var pXc = (pWidth - 1) / 2;
			var pYc = (pHeight - 1) / 2;

			// Get tile index containing the pixel
			tX = pXc / pTileWidth;
			tY = pYc / pTileHeight;

			// Readjust pX, pY to the centre of the tile
			pX = tX * pTileWidth + pTileWidth / 2;
			pY = tY * pTileHeight + pTileHeight / 2;

			UpdateViewport ();
		}

		public void UpdateCamera(Vector2f center)
		{
			var pXc = (int)center.X +(pWidth) / 2;
			var pYc = (int)center.Y +(pHeight) / 2;
			// Get tile index containing the pixel
			tX = pXc / pTileWidth;
			tY = pYc / pTileHeight;

			// Readjust pX, pY to the centre of the tile
			pX = pXc;
			pY = pYc;

			RescaleCamera ();
		}

		private void RescaleCanvas()
		{
			// Screen pixel count
			var pWindowWidth = game.Size.X;
			var pWindowHeight = game.Size.Y;

			// Determine the minimum scaling
			var xScale = (float)pWindowWidth / (pTileWidth * tMaxWidth);
			var yScale = (float)pWindowHeight / (pTileHeight * tMaxHeight);
			tileScale = Math.Max(xScale, yScale);
			tWidth = (int)Math.Round(pWindowWidth / (pTileWidth * tileScale));
			tHeight = (int)Math.Round(pWindowHeight / (pTileHeight * tileScale));

			// Virtual height is prescribed (i.e. window-independent)
			pHeight = (int)Math.Round(pWindowHeight / tileScale);
			pWidth = (int)Math.Round(pWindowWidth / tileScale);
		}

		private void RescaleCamera()
		{
			// Visible tile range (tStart <= t < tEnd)
			tStartX = tX - (tWidth - 1) / 2 - tHalo;
			tEndX = tX + (tWidth - 1) / 2 + 1 + tHalo;
			tStartY = tY - (tHeight - 1) / 2 - tHalo;
			tEndY = tY + (tHeight - 1) / 2 + 1 + tHalo;

			camera = new Vector2f((float)pX, (float)pY);
			origin = camera - new Vector2f((float)(pWidth/2), (float)(pHeight/2));
		}

		public void UpdateViewport()
		{
			RescaleCanvas();
			RescaleCamera ();
		}
	}
}