text:
#include <llvm/Support/DynamicLibrary.h>
#include <llvm/IR/DerivedTypes.h>
#include <llvm/IR/Function.h>
#include <llvm/IR/Module.h>

extern "C" {
#include "lprefix.h"
#include "ldebug.h"
#include "lfunc.h"
#include "lgc.h"
#include "lopcodes.h"
#include "luaconf.h"
#include "lvm.h"
#include "ltable.h"
}

#include "lllruntime.h"

namespace {

#if 0
/* useful debug function: */
static void dumpstack (StkId begin, StkId end) {
  printf("Stack dump:\n");
  for (StkId o = begin; o != end; ++o) {
    printf("  %p", o);
    switch (novariant(ttype(o))) {
      case LUA_TNIL:
        printf("  nil\n"); break;
      case LUA_TBOOLEAN:
        printf("  boolean: %s\n", bvalue(o) ? "true" : "false"); break;
      case LUA_TLIGHTUSERDATA:
        printf("  light user data: %p\n", pvalue(o)); break;
      case LUA_TNUMBER:
        printf("  number: %f\n", nvalue(o)); break;
      case LUA_TSTRING:
        printf("  string: %s\n", getstr(o)); break;
      case LUA_TTABLE:
        printf("  table: %p\n", hvalue(o)); break;
      case LUA_TFUNCTION:
        printf("  function: %p\n", clvalue(o)); break;
      case LUA_TUSERDATA:
        printf("  heavy user data: %p\n", uvalue(o)); break;
      case LUA_TTHREAD:
        printf("  thread: %p\n", thvalue(o)); break;
      default:
        printf("  Unknown type: %d\n", ttype(o)); break;
    }
  }
}
#endif

lua_Number LLLNumMod(lua_Number lhs, lua_Number rhs) {
    lua_Number result;
    luai_nummod(0, lhs, rhs, result);
    return result;
}

}

static void lll_checkcg (lua_State *L, CallInfo *ci, TValue *c) {
    // From lvm.c checkGC(L,c)
    luaC_condGC(L, L->top = (c), L->top = ci->top);
    luai_threadyield(L);
}

static Table *lll_newtable (lua_State *L, TValue *r) {
  Table *t = luaH_new(L);
  sethvalue(L, r, t);
  return t;
}

static void lll_upvalbarrier (lua_State *L, UpVal *uv) {
    luaC_upvalbarrier(L, uv);
}

static int forlimit (const TValue *obj, lua_Integer *p, lua_Integer step,
                     int *stopnow) {
  *stopnow = 0;  /* usually, let loops run */
  if (!luaV_tointeger(obj, p, (step < 0 ? 2 : 1))) {  /* not fit in integer? */
    lua_Number n;  /* try to convert to float */
    if (!tonumber(obj, &n)) /* cannot convert to float? */
      return 0;  /* not a number */
    if (luai_numlt(0, n)) {  /* if true, float is larger than max integer */
      *p = LUA_MAXINTEGER;
      if (step < 0) *stopnow = 1;
    }
    else {  /* float is smaller than min integer */
      *p = LUA_MININTEGER;
      if (step >= 0) *stopnow = 1;
    }
  }
  return 1;
}

static void lll_forprep (lua_State *L, TValue *ra)
{
    TValue *init = ra;
    TValue *plimit = ra + 1;
    TValue *pstep = ra + 2;
    lua_Integer ilimit;
    int stopnow;
    if (ttisinteger(init) && ttisinteger(pstep) &&
        forlimit(plimit, &ilimit, ivalue(pstep), &stopnow)) {
      /* all values are integer */
      lua_Integer initv = (stopnow ? 0 : ivalue(init));
      setivalue(plimit, ilimit);
      setivalue(init, initv - ivalue(pstep));
    }
    else {  /* try making all values floats */
      lua_Number ninit; lua_Number nlimit; lua_Number nstep;
      if (!tonumber(plimit, &nlimit))
        luaG_runerror(L, "'for' limit must be a number");
      setfltvalue(plimit, nlimit);
      if (!tonumber(pstep, &nstep))
        luaG_runerror(L, "'for' step must be a number");
      setfltvalue(pstep, nstep);
      if (!tonumber(init, &ninit))
        luaG_runerror(L, "'for' initial value must be a number");
      setfltvalue(init, luai_numsub(L, ninit, nstep));
    }
}

static void lll_setlist(lua_State* L, TValue* ra, int fields, int n)
{
    Table* h = hvalue(ra);
    unsigned int last = fields + n;
    if (last > h->sizearray)
        luaH_resizearray(L, h, last);
    for (; n > 0; n--) {
        TValue* val = ra + n;
        luaH_setint(L, h, last--, val);
        luaC_barrierback(L, h, val);
    }
}

static LClosure *getcached (Proto *p, UpVal **encup, StkId base) {
  LClosure *c = p->cache;
  if (c != NULL) {  /* is there a cached closure? */
    int nup = p->sizeupvalues;
    Upvaldesc *uv = p->upvalues;
    int i;
    for (i = 0; i < nup; i++) {  /* check whether it has right upvalues */
      TValue *v = uv[i].instack ? base + uv[i].idx : encup[uv[i].idx]->v;
      if (c->upvals[i]->v != v)
        return NULL;  /* wrong upvalue; cannot reuse closure */
    }
  }
  return c;  /* return cached closure (or NULL if no cached closure) */
}

static void pushclosure (lua_State *L, Proto *p, UpVal **encup, StkId base,
                         StkId ra) {
  int nup = p->sizeupvalues;
  Upvaldesc *uv = p->upvalues;
  int i;
  LClosure *ncl = luaF_newLclosure(L, nup);
  ncl->p = p;
  setclLvalue(L, ra, ncl);  /* anchor new closure in stack */
  for (i = 0; i < nup; i++) {  /* fill in its upvalues */
    if (uv[i].instack)  /* upvalue refers to local variable? */
      ncl->upvals[i] = luaF_findupval(L, base + uv[i].idx);
    else  /* get upvalue from enclosing function */
      ncl->upvals[i] = encup[uv[i].idx];
    ncl->upvals[i]->refcount++;
    /* new closure is white, so we do not need a barrier here */
  }
  if (!isblack(p))  /* cache will not break GC invariant? */
    p->cache = ncl;  /* save it on cache for reuse */
}

static void lll_closure(lua_State* L, LClosure* cl, TValue* base, TValue* ra,
        int bx) {
    Proto *p = cl->p->p[bx];
    LClosure *ncl = getcached(p, cl->upvals, base);  /* cached closure */
    if (ncl == NULL)  /* no match? */
        pushclosure(L, p, cl->upvals, base, ra);  /* create a new one */
    else
        setclLvalue(L, ra, ncl);  /* push cashed closure */
}

static void lll_checkstack(lua_State* L, int n) {
    luaD_checkstack(L, n);
}

namespace lll {

Runtime* Runtime::instance_ = nullptr;

Runtime::Runtime() :
    context_(llvm::getGlobalContext()) {
    InitTypes();
    InitFunctions();
}

Runtime* Runtime::Instance() {
    if (!instance_)
        instance_ = new Runtime();
    return instance_;
}

llvm::Type* Runtime::GetType(const std::string& name) {
    AssertKeyExists(types_, name);
    return types_[name];
}

llvm::Function* Runtime::GetFunction(llvm::Module* module,
                                     const std::string& name) {
    AssertKeyExists(functions_, name);
    auto function = module->getFunction(name);
    if (!function)
        function = llvm::Function::Create(functions_[name],
                llvm::Function::ExternalLinkage, name, module);
    return function;
}

llvm::Type* Runtime::MakeIntT(int nbytes) {
    return llvm::IntegerType::get(context_, 8 * nbytes);
}

void Runtime::InitTypes() {
    #define ADDTYPE(T) AddStructType(#T, sizeof(T))

    ADDTYPE(global_State);
    ADDTYPE(lua_State);
    ADDTYPE(CallInfo);
    ADDTYPE(LClosure);
    ADDTYPE(Proto);
    ADDTYPE(UpVal);
    ADDTYPE(GCObject);
    ADDTYPE(Table);
    ADDTYPE(TString);

    std::vector<llvm::Type*> ttvaluefields = {
        MakeIntT(sizeof(Value)),
        MakeIntT(sizeof(int)),
        MakeIntT(sizeof(int))
    };
    auto ttvalue = llvm::StructType::create(ttvaluefields, "TValue");
    types_["TValue"] = llvm::PointerType::get(ttvalue, 0);

    types_["int"] = MakeIntT(sizeof(int));
    types_["lua_Integer"] = MakeIntT(sizeof(lua_Integer));

    #if LUA_FLOAT_TYPE == LUA_FLOAT_FLOAT
    types_["lua_Number"] = llvm::Type::getFloatTy(context_);
    #elif LUA_FLOAT_TYPE == LUA_FLOAT_LONGDOUBLE
    types_["lua_Number"] = llvm::Type::getFP128Ty(context_);
    #elif LUA_FLOAT_TYPE == LUA_FLOAT_DOUBLE
    types_["lua_Number"] = llvm::Type::getDoubleTy(context_);
    #endif
}

void Runtime::InitFunctions() {
    #define ADDFUNCTION(function, ret, ...) { \
        std::vector<llvm::Type*> args = {__VA_ARGS__}; \
        auto type = llvm::FunctionType::get(ret, args, false); \
        auto funcptr = reinterpret_cast<void*>(function); \
        AddFunction(STRINGFY2(function), type, funcptr); }

    auto tstate = types_["lua_State"];
    auto tclosure = types_["LClosure"];
    auto ttvalue = types_["TValue"];
    auto tci = types_["CallInfo"];
    auto ttable = types_["Table"];
    auto ttstring = types_["TString"];
    auto tupval = types_["UpVal"];
    auto tluanumber = types_["lua_Number"];
    auto tluanumberptr = llvm::PointerType::get(tluanumber, 0);
    auto tluainteger = types_["lua_Integer"];
    auto tluaintegerptr = llvm::PointerType::get(tluainteger, 0);
    auto tvoid = llvm::Type::getVoidTy(context_);
    auto tint = MakeIntT(sizeof(int));

    // LLL
    ADDFUNCTION(LLLNumMod, tluanumber, tluanumber, tluanumber);

    // Deprecated lll
    ADDFUNCTION(lll_checkcg, tvoid, tstate, tci, ttvalue);
    ADDFUNCTION(lll_newtable, ttable, tstate, ttvalue);
    ADDFUNCTION(lll_upvalbarrier, tvoid, tstate, tupval);
    ADDFUNCTION(lll_forprep, tvoid, tstate, ttvalue);
    ADDFUNCTION(lll_setlist, tvoid, tstate, ttvalue, tint, tint);
    ADDFUNCTION(lll_closure, tvoid, tstate, tclosure, ttvalue, ttvalue, tint);
    ADDFUNCTION(lll_checkstack, tvoid, tstate, tint);

    // math.h
    ADDFUNCTION(l_mathop(floor), tluanumber, tluanumber);
    ADDFUNCTION(l_mathop(pow), tluanumber, tluanumber, tluanumber);

    // ldo.h
    ADDFUNCTION(luaD_callnoyield, tvoid, tstate, ttvalue, tint);

    // lfunc.h
    ADDFUNCTION(luaF_close, tvoid, tstate, ttvalue);

    // lgc.h
    ADDFUNCTION(luaC_barrierback_, tvoid, tstate, ttable);

    // ltable.h
    ADDFUNCTION(luaH_getint, ttvalue, ttable, tluainteger);
    ADDFUNCTION(luaH_getshortstr, ttvalue, ttable, ttstring);
    ADDFUNCTION(luaH_getstr, ttvalue, ttable, ttstring);
    ADDFUNCTION(luaH_get, ttvalue, ttable, ttvalue);
    ADDFUNCTION(luaH_resize, tvoid, tstate, ttable, tint, tint);

    // ltm.h
    ADDFUNCTION(luaT_gettm, ttvalue, ttable, tint, ttstring);
    ADDFUNCTION(luaT_trybinTM, tvoid, tstate, ttvalue, ttvalue, ttvalue, tint);

    // lvm.h
    ADDFUNCTION(luaV_concat, tvoid, tstate, tint);
    ADDFUNCTION(luaV_div, tluainteger, tstate, tluainteger, tluainteger);
    ADDFUNCTION(luaV_equalobj, tint, tstate, ttvalue, ttvalue);
    ADDFUNCTION(luaV_finishget, tvoid, tstate, ttvalue, ttvalue, ttvalue,
            ttvalue);
    ADDFUNCTION(luaV_finishset, tvoid, tstate, ttvalue, ttvalue, ttvalue,
            ttvalue);
    ADDFUNCTION(luaV_lessequal, tint, tstate, ttvalue, ttvalue);
    ADDFUNCTION(luaV_lessthan, tint, tstate, ttvalue, ttvalue);
    ADDFUNCTION(luaV_mod, tluainteger, tstate, tluainteger, tluainteger);
    ADDFUNCTION(luaV_objlen, tvoid, tstate, ttvalue, ttvalue)
    ADDFUNCTION(luaV_shiftl, tluainteger, tluainteger, tluainteger);
    ADDFUNCTION(luaV_tointeger, tint, ttvalue, tluaintegerptr, tint);
    ADDFUNCTION(luaV_tonumber_, tint, ttvalue, tluanumberptr);
}

void Runtime::AddStructType(const std::string& name, size_t size) {
    std::vector<llvm::Type*> memt = {MakeIntT(size)};
    auto structt = llvm::StructType::create(memt, name);
    types_[name] = llvm::PointerType::get(structt, 0);
}

void Runtime::AddFunction(const std::string& name, llvm::FunctionType* type,
                          void* address) {
    functions_[name] = type;
    llvm::sys::DynamicLibrary::AddSymbol(name, address);
}

}


text:
<?php

use yii\db\Migration;

class m151025_190245_calendar_event extends Migration
{
    public function up()
    {
        $this->renameTable('{{%calendar}}', '{{%calendar_event}}');

        $this->addColumn('{{%calendar_event}}', 'name', 'varchar(255) NOT NULL AFTER id');

        $this->addColumn('{{%calendar_event}}', 'imageId', 'int(11) unsigned AFTER name');

        $this->addForeignKey('calendar_image', '{{%calendar_event}}', 'imageId', '{{%image}}', 'id', 'set null', 'cascade');
    }

    public function down()
    {
        $this->dropForeignKey('calendar_image', '{{%calendar_event}}');

        $this->dropColumn('{{%calendar_event}}', 'name');

        $this->dropColumn('{{%calendar_event}}', 'imageId');

        $this->renameTable('{{%calendar_event}}', '{{%calendar}}');
    }
}

redpajama_set_name: RedPajamaGithub


text: Magnet League Fixture Maker


text:
test:
	./node_modules/.bin/mocha --reporter spec --timeout 5000

.PHONY: test


text:
<?php

namespace Symfony\Component\RateLimiter\Util;

/**
 * @author Wouter de Jong <wouter@wouterj.nl>
 *
 * @internal
 */
final class TimeUtil
{
    public static function dateIntervalToSeconds(\DateInterval $interval): int
    {
        return (float) $interval->format('%s')      // seconds
            + $interval->format('%i') * 60          // minutes
            + $interval->format('%H') * 3600        // hours
            + $interval->format('%d') * 3600 * 24   // days
            ;
    }
}


text:
import sys
sys.path.append('../py')

from iroha import *
from iroha.iroha import *

d = IDesign()
mod = IModule(d, "mod")
tab = ITable(mod)
st1 = IState(tab)
st2 = IState(tab)
tab.states.append(st1)
tab.states.append(st2)
tab.initialSt = st1
design_tool.AddNextState(st1, st2)

res = design_tool.CreateEmbeddedExtTaskCall(tab, "mod_hello", "mod_hello.v", "clk", "rst_n")

design_tool.AddEmbeddedModuleIO(res, ["x:32", "y:32"], ["z"])

insn = IInsn(res)
st1.insns.append(insn)

design_tool.ValidateIds(d)

w = DesignWriter(d)
w.Write()


text:
\chapter{Discusión}
\thispagestyle{empty}

Tu interpretación de los resultados según los objetivos...

\section{Acerca de la Batimetría}

La grilla batimétrica obtenida en el estudio es de alta resolución ...

\section{Acerca de los Posibles Ambientes de Deposición Continua}

El mapa de predicción de ambientes de deposición continua...


text:
require('coffee-script/register');

var nodeUtil = require("util"),
	events = require("events"),
	path = require("path"),
	fs = require("fs"),
	// pull request already submitted to json2json project
	// TODO: swtich back to json2json module once the pull request is merged
	j2j = require('json2json-openui5'),
	extend = require('extend'),
	mkdirp = require("mkdirp"),
	async = require("async"),
	configs = require("./config.js"),
	util = require("./util.js"),
	fileContent = require("./fileContent.js");

var aUI5Tags = ["ar", "ar_EG", "ar_SA", "bg", "ca", "cs", "da", "de", "de_AT", "de_CH", "el", "el_CY",
                	"en", "en_AU", "en_GB", "en_HK", "en_IE", "en_IN", "en_NZ", "en_PG", "en_SG", "en_ZA", "es",
                	"es_AR", "es_BO", "es_CL", "es_CO", "es_MX", "es_PE", "es_UY", "es_VE", "et", "fa", "fi", "fr",
                	"fr_BE", "fr_CA", "fr_CH", "fr_LU", "he", "hi", "hr", "hu", "id", "it", "it_CH", "ja", "ko", "lt",
                	"lv", "nb", "nl", "nl_BE", "pl", "pt", "pt_PT", "ro", "ru", "ru_UA", "sk", "sl", "sr", "sv",
                	"th", "tr", "uk", "vi", "zh_CN", "zh_HK", "zh_SG", "zh_TW"];

/**
 * Generates the UI5 locale JSON files using the original JSON files.
 */
function Generator(sOutputFolder, bPrettyPrint) {
	if (!(this instanceof Generator)) {
		return new Generator(sOutputFolder, bPrettyPrint);
	}
	this._sOutputFolder = sOutputFolder;
	this._bPrettyPrint = bPrettyPrint;
	events.EventEmitter.call(this);
}

function getCLDRTag(sUI5Tag) {
	switch(sUI5Tag) {
		case "zh_CN": return "zh-Hans-CN";
		case "zh_SG": return "zh-Hans-SG";
		case "zh_TW": return "zh-Hant-TW";
		case "zh_HK": return "zh-Hans-HK";
		default: return sUI5Tag.replace(/_/, "-");
	}
}

nodeUtil.inherits(Generator, events.EventEmitter);

Generator.prototype.start = function() {
	var sSrcFolder = "node_modules",
		sOutputFolder = this._sOutputFolder,
		self = this,
		sLicense = "This file has been derived from Unicode Common Locale Data Repository (CLDR) files (http://cldr.unicode.org). See the copyright and permission notice in the Unicode-Data-Files-LICENSE.txt available at the same location as this file or visit http://www.unicode.org/copyright.html",
		sFolderPathSupple = path.join(sSrcFolder, "cldr-core", "supplemental"),
		sFilePath,
		sFileName,
		oData,
		oResult = {},
		oOutputData,
		aTasks = [];

	util.setSupplePath(sFolderPathSupple);

	var mCurrencyDigits = util.getCurrencyDigits();

	aUI5Tags.forEach(function(sUI5Tag) {
		var sCLDRTag = getCLDRTag(sUI5Tag),
			sPathTag = sCLDRTag,
			sLanguage = sUI5Tag.split("_")[0],
			sCalendarPref = util.getCalendarPreference(sCLDRTag),
			aSubTasks,
			oCurrencyFormatShort;

		// insert the license string
		oResult = {"__license": sLicense};

		// process each of the configs
		configs.forEach(function(mConfig) {
			// Ugly file path fallback, latest CLDR does not contain CN/TW files anymore
			if (sCLDRTag == "zh-Hans-CN") sPathTag = "zh-Hans";
			if (sCLDRTag == "zh-Hant-TW") sPathTag = "zh-Hant";
			sFileName = path.join(sSrcFolder, mConfig.packageName, "main", sPathTag, mConfig.fileName);
			oData = fileContent.getContent(sFileName).main[sPathTag];
			oOutputData = new j2j.ObjectTemplate(mConfig.template).transform(oData);
			// extends the result with transformed data using the config
			extend(true, oResult, oOutputData);
		});

		if (oResult.rtl) {
			// If the character order is right-to-left,
			// insert a RLM marker in front of the first 0 to make the number to be displayed
			// in the same direction as the scale
			oCurrencyFormatShort = oResult["currencyFormat-short"];
			Object.keys(oCurrencyFormatShort).forEach(function(sKey) {
				oCurrencyFormatShort[sKey] = oCurrencyFormatShort[sKey].replace("0", "\u200f0");
			});
		}

		// Workround for arabic short number million issue, can be removed, when
		// http://unicode.org/cldr/trac/ticket/9859
		// is resolved
		if (sCLDRTag.indexOf("ar") === 0) {
			oResult["decimalFormat-short"] = oResult["decimalFormat-long"];
		}

		// extend result with static data:
		//	currencyDigits
		//  pluralRules
		//	weekData
		//  calendarData
		extend(oResult, {currencyDigits: mCurrencyDigits});
		extend(oResult, util.getPluralRules(sCLDRTag));
		extend(oResult, util.getWeekData(sCLDRTag));
		extend(oResult, util.getTimeData(sCLDRTag));
		extend(oResult, util.getCalendarData());

		if (sCalendarPref) {
			// if calendar preference exits, also extend the result with it
			extend(oResult, {
				"calendarPreference": sCalendarPref
			});
		}

		fileContent.clearCache();

		// The following two tasks are run in series: create folder and write file
		aSubTasks = [
			function(callback) {
				mkdirp(sOutputFolder, function(err) {
					callback(err);
				});
			},
			(function(r) {
				return function(callback) {
					var sPath = path.resolve(path.join(sOutputFolder, sUI5Tag + '.json'));
					fs.writeFile(sPath, JSON.stringify(r, null, self._bPrettyPrint ? '\t' : 0), function(err) {
						callback(err, sPath);
					});
				};
			})(oResult)
		];

		// The task for writing each JSON file is done in parallel with the other file writing
		aTasks.push(function(callback) {
			// execute the aSubTasks
			async.series(aSubTasks, function(err, results) {
				if (!err) {
					self.emit("localeJSONReady", results[1]);
				} else {
					self.emit("error", err);
				}
				callback(err, results[1]);
			});
		});
	});

	// execute the aTasks
	async.parallel(aTasks, function(err, results) {
		if (!err) {
			self.emit("allLocaleJSONReady", results);
		} else {
			self.emit("error", err);
		}
	});

	return this;
};

module.exports = Generator;


text:
{% extends "base.html" %}
{% load i18n %}

{% block page_class %}Contact Page{% endblock %}
{% block content %}

Thank you!

Message sent. We'll get back to you shortly.

{% endblock %}


text:
/*
 * Global definitions for the line printer system.
 */

extern char	*AF;		/* accounting file */
extern long	 BR;		/* baud rate if lp is a tty */
extern char	*CF;		/* name of cifplot filter (per job) */
extern long	 CT;		/* TCP connection timeout */
extern char	*DF;		/* name of tex filter (per job) */
extern long	 DU;		/* daeomon user-id */
extern char	*FF;		/* form feed string */
extern char	*GF;		/* name of graph(1G) filter (per job) */
extern long	 HL;		/* print header last */
extern char	*IF;		/* name of input filter (created per job) */
extern char	*LF;		/* log file for error messages */
extern char	*LO;		/* lock file name */
extern char	*LP;		/* line printer device name */
extern long	 MC;		/* maximum number of copies allowed */
extern long      MX;		/* maximum number of blocks to copy */
extern char	*NF;		/* name of ditroff(1) filter (per job) */
extern char	*OF;		/* name of output filter (created once) */
extern long	 PL;		/* page length */
extern long	 PW;		/* page width */
extern long	 PX;		/* page width in pixels */
extern long	 PY;		/* page length in pixels */
extern char	*RF;		/* name of fortran text filter (per job) */
extern char	*RG;		/* restricted group */
extern char	*RM;		/* remote machine name */
extern char	*RP;		/* remote printer name */
extern long	 RS;		/* restricted to those with local accounts */
extern long	 RW;		/* open LP for reading and writing */
extern long	 SB;		/* short banner instead of normal header */
extern long	 SC;		/* suppress multiple copies */
extern char	*SD;		/* spool directory */
extern long	 SF;		/* suppress FF on each print job */
extern long	 SH;		/* suppress header page */
extern char	*ST;		/* status file name */
extern char	*TF;		/* name of troff(1) filter (per job) */
extern char	*TR;		/* trailer string to be output when Q empties */
extern char	*MS;		/* mode set, a la stty */
extern char	*VF;		/* name of raster filter (per job) */

extern char	line[BUFSIZ];
extern char	*bp;		/* pointer into printcap buffer */
extern char	*name;		/* program name */
extern char	*printer;	/* printer name */
				/* host machine name */
extern char	host[MAXHOSTNAMELEN];
extern char	*from;		/* client's machine name */
extern int	remote;		/* true if sending files to a remote host */
extern char	*printcapdb[];  /* printcap database array */

extern int	requ[];		/* job number of spool entries */
extern int	requests;	/* # of spool requests */
extern char	*user[];        /* users to process */
extern int	users;		/* # of users in user array */
extern char	*person;	/* name of person doing lprm */
extern char	*name;

/*
 * Structure used for building a sorted list of control files.
 */
struct queue {
	time_t	q_time;			/* modification time */
	char	q_name[MAXNAMLEN+1];	/* control file name */
};

#include <sys/cdefs.h>

__BEGIN_DECLS
struct dirent;

void     blankfill __P((int));
char	*checkremote __P((void));
int      chk __P((char *));
void     displayq __P((int));
void     dump __P((char *, char *, int));
void	 fatal __P((const char *, ...));
int	 getline __P((FILE *));
int	 getport __P((char *, int));
int	 getq __P((struct queue *(*[])));
void     header __P((void));
void     inform __P((char *));
int      inlist __P((char *, char *));
int      iscf __P((struct dirent *));
int      isowner __P((char *, char *));
void     ldump __P((char *, char *, int));
int      lockchk __P((char *));
void     prank __P((int));
void     process __P((char *));
void     rmjob __P((void));
void     rmremote __P((void));
void     show __P((char *, char *, int));
int      startdaemon __P((char *));
void     delay __P((int));
__END_DECLS


text:
#import <XCTest/XCTest.h>
#import "FBSnapshotTestController.h"

@interface FBSnapshotControllerTests : XCTestCase

@end

@implementation FBSnapshotControllerTests

- (UIImage *)bundledImageNamed:(NSString *)name type:(NSString *)type
{
    NSBundle *bundle = [NSBundle bundleForClass:[self class]];
    NSString *path = [bundle pathForResource:name ofType:type];
    NSData *data = [[NSData alloc] initWithContentsOfFile:path];
    return [[UIImage alloc] initWithData:data];
}

- (void)testCompareReferenceImageToImageShouldBeEqual
{
    UIImage *referenceImage = [self bundledImageNamed:@"square" type:@"png"];
    XCTAssertNotNil(referenceImage, @"");
    UIImage *testImage = [self bundledImageNamed:@"square-copy" type:@"png"];
    XCTAssertNotNil(testImage, @"");
    FBSnapshotTestController *controller = [[FBSnapshotTestController alloc] initWithTestClass:nil];
    XCTAssertTrue([controller compareReferenceImage:referenceImage toImage:testImage error:nil], @"");
}

- (void)testCompareReferenceImageToImageShouldNotBeEqual
{
    UIImage *referenceImage = [self bundledImageNamed:@"square" type:@"png"];
    XCTAssertNotNil(referenceImage, @"");
    UIImage *testImage = [self bundledImageNamed:@"square_with_text" type:@"png"];
    XCTAssertNotNil(testImage, @"");
    FBSnapshotTestController *controller = [[FBSnapshotTestController alloc] initWithTestClass:nil];
    XCTAssertFalse([controller compareReferenceImage:referenceImage toImage:testImage error:nil], @"");
}

@end


text:
<?php declare(strict_types=1);
/**
 * @license MIT
 * @author Samuel Adeshina <samueladeshina73@gmail.calculhmac(clent, data)om>
 *
 * This file is part of the EmmetBlue project, please read the license document
 * available in the root level of the project
 */
namespace EmmetBlue\Plugins\Pharmacy\DispensoryStoreLink;

use EmmetBlue\Core\Builder\BuilderFactory as Builder;
use EmmetBlue\Core\Factory\DatabaseConnectionFactory as DBConnectionFactory;
use EmmetBlue\Core\Factory\DatabaseQueryFactory as DBQueryFactory;
use EmmetBlue\Core\Builder\QueryBuilder\QueryBuilder as QB;
use EmmetBlue\Core\Exception\SQLException;
use EmmetBlue\Core\Exception\UndefinedValueException;
use EmmetBlue\Core\Session\Session;
use EmmetBlue\Core\Logger\DatabaseLog;
use EmmetBlue\Core\Logger\ErrorLog;
use EmmetBlue\Core\Constant;

/**
 * class DispensoryStoreLink.
 *
 * DispensoryStoreLink Controller
 *
 * @author Samuel Adeshina <samueladeshina73@gmail.com>
 * @since v0.0.1 08/06/2016 14:20
 */
class DispensoryStoreLink
{
	public static function create(array $data)
    {
        $dispensory = $data['dispensory'] ?? null;
        $store = $data["store"] ?? null;

        try
        {
        	$result = DBQueryFactory::insert('Pharmacy.DispensoryStoreLink', [
                'Dispensory'=>$dispensory,
                'Store'=>$store
            ]);

            return $result;
        }
        catch (\PDOException $e)
        {
            throw new SQLException(sprintf(
                "Unable to process request (new link creation request), %s",
                $e->getMessage()
            ), Constant::UNDEFINED);
        }
    }

    /**
     * Modifies the content of a dispensory group record
     */
    public static function edit(int $resourceId, array $data)
    {
        $updateBuilder = (new Builder("QueryBuilder", "Update"))->getBuilder();

        try
        {
            $updateBuilder->table("Pharmacy.DispensoryStoreLink");
            $updateBuilder->set($data);
            $updateBuilder->where("LinkID = $resourceId");

            $result = (
                    DBConnectionFactory::getConnection()
                    ->exec((string)$updateBuilder)
                );

            return $result;
        }
        catch (\PDOException $e)
        {
            throw new SQLException(sprintf(
                "Unable to process update, %s",
                $e->getMessage()
            ), Constant::UNDEFINED);
        }
    }

    /**
     * Returns dispensory group data
     *
     * @param int $resourceId optional
     */
    public static function view(int $resourceId = 0, array $data = [])
    {
        $selectBuilder = (new Builder("QueryBuilder", "Select"))->getBuilder();

        try
        {
            if (empty($data)){
                $selectBuilder->columns("a.LinkID, b.*");
            }
            else {
                $selectBuilder->columns(implode(", ", $data));
            }

            $selectBuilder->from("Pharmacy.DispensoryStoreLink a");
            $selectBuilder->innerJoin("Pharmacy.EligibleDispensory b", "a.Dispensory = b.EligibleDispensoryID")->innerJoin(
                "Pharmacy.Store c", "a.Store = c.StoreID"
            );

            if ($resourceId !== 0){
                $selectBuilder->where("LinkID = $resourceId");
            }

            $result = (
                    DBConnectionFactory::getConnection()
                    ->query((string)$selectBuilder)
                )->fetchAll(\PDO::FETCH_ASSOC);

            return $result;
        }
        catch (\PDOException $e)
        {
            throw new SQLException(sprintf(
                "Unable to retrieve requested data, %s",
                $e->getMessage()
            ), Constant::UNDEFINED);
        }
    }

    public static function viewByDispensory(int $resourceId = 0, array $data = [])
    {
        $selectBuilder = (new Builder("QueryBuilder", "Select"))->getBuilder();

        try
        {
            if (empty($data)){
                $selectBuilder->columns("a.LinkID, b.*");
            }
            else {
                $selectBuilder->columns(implode(", ", $data));
            }

            $selectBuilder->from("Pharmacy.DispensoryStoreLink a");
            $selectBuilder->innerJoin("Pharmacy.Store b", "a.Store = b.StoreID");

            $selectBuilder->where("a.Dispensory = $resourceId");

            $result = (
                    DBConnectionFactory::getConnection()
                    ->query((string)$selectBuilder)
                )->fetchAll(\PDO::FETCH_ASSOC);

            return $result;
        }
        catch (\PDOException $e)
        {
            throw new SQLException(sprintf(
                "Unable to retrieve requested data, %s",
                $e->getMessage()
            ), Constant::UNDEFINED);
        }
    }

    public static function delete(int $resourceId)
    {
        $deleteBuilder = (new Builder("QueryBuilder", "Delete"))->getBuilder();

        try
        {
            $deleteBuilder
                ->from("Pharmacy.DispensoryStoreLink")
                ->where("LinkID = $resourceId");

            $result = (
                    DBConnectionFactory::getConnection()
                    ->exec((string)$deleteBuilder)
                );

            return $result;
        }
        catch (\PDOException $e)
        {
            throw new SQLException(sprintf(
                "Unable to process delete request, %s",
                $e->getMessage()
            ), Constant::UNDEFINED);
        }
    }
}


text:
<?php

// Registering our own autoloader, with a closure (unnamed function)
spl_autoload_register(function ($class) {
    // Search for any unknown class (getting there) in the `Pages` folder
    include '../Pages/'.ucfirst($class).'.php';
});

// Getting the class name from the HTTP request URI, trimming leading and trailing `/`
$className = trim($_SERVER['REQUEST_URI'], '/');

// If we are on `/`, user do want the homepage
if ($className === '') {
    $className = 'homepage';
}

// Searching for the class (will use our custom autoload function)
if (class_exists($className)) {
    // Creating the PageModel object
    $page = new $className();
    // Rendering it
    $page->render();
} else {
    // PageModel not found
    echo 'Unknown page.';
}


text:
// Copyright (c) .NET Foundation. All rights reserved.
// Licensed under the MIT license. See LICENSE file in the project root for details.

using System;
using System.Collections;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.Drawing.Text;
using System.Globalization;
using System.Windows.Forms;
using OpenLiveWriter.CoreServices.Layout;
using OpenLiveWriter.HtmlParser.Parser;
using OpenLiveWriter.ApplicationFramework;
using OpenLiveWriter.ApplicationFramework.Skinning;
using OpenLiveWriter.Controls;
using OpenLiveWriter.CoreServices;
using OpenLiveWriter.Extensibility.BlogClient;
using OpenLiveWriter.Interop.Windows;
using OpenLiveWriter.Localization;
using OpenLiveWriter.Localization.Bidi;

namespace OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl
{
	/// <summary>
	/// Summary description for CategoryDisplayForm.
	/// </summary>
	internal class CategoryDisplayFormM1 : MiniForm
	{
		public CategoryDisplayFormM1(Control parentControl, CategoryContext categoryContext)
		{
			SuppressAutoRtlFixup = true;
			// save references and signup for changed event
			_parentControl = parentControl;
			_categoryContext = categoryContext;
			_categoryContext.Changed += new CategoryContext.CategoryChangedEventHandler(_categoryContext_Changed);

			// standard designer stuff
			InitializeComponent();

			this.buttonAdd.Text = Res.Get(StringId.AddButton2);

			// mini form behavior
			DismissOnDeactivate = true;

			// dynamic background colors based on theme
			BackColor = ColorizedResources.Instance.FrameGradientLight ;
			categoryRefreshControl.BackColor = ColorizedResources.Instance.FrameGradientLight ;
			categoryContainerControl.BackColor = SystemColors.Window ;

			// dynamic layout depending upon whether we support adding categories
			if ( categoryContext.SupportsAddingCategories )
			{
				textBoxAddCategory.MaxLength = categoryContext.MaxCategoryNameLength ;
			}
			else
			{
				int gap = categoryContainerControl.Top - panelAddCategory.Top ;
				panelAddCategory.Visible = false ;
				categoryContainerControl.Top = panelAddCategory.Top + 2 ;
				categoryContainerControl.Height += gap ;
			}

			// dynamic layout depending upon whether we support heirarchical categories
			if ( !categoryContext.SupportsHierarchicalCategories )
			{
				textBoxAddCategory.Width += (comboBoxParent.Right - textBoxAddCategory.Right);
				comboBoxParent.Visible = false ;
			}

			// initialize add textbox
			ClearAddTextBox() ;

			// initialize category control
			categoryRefreshControl.Initialize(_categoryContext);
		}

		public int MaxDropDownWidth
		{
			get { return _maxDropDownWidth; }
			set { _maxDropDownWidth = value; }
		}

		public int MinDropDownWidth
		{
			get { return _minDropDownWidth; }
			set { _minDropDownWidth = value; }
		}

		private int _maxDropDownWidth = 260;
		private int _minDropDownWidth = 104;

		protected override void OnLoad(EventArgs e)
		{
			base.OnLoad(e);

			RefreshParentCombo();

			if (panelAddCategory.Visible)
			{
				if (comboBoxParent.Visible)
				{
					DisplayHelper.AutoFitSystemButton(buttonAdd);
					using (new AutoGrow(this, AnchorStyles.Bottom | AnchorStyles.Right, false))
					{
						textBoxAddCategory.Width = buttonAdd.Right - textBoxAddCategory.Left;

						DisplayHelper.AutoFitSystemCombo(comboBoxParent, 0, int.MaxValue, true);
						comboBoxParent.Left = textBoxAddCategory.Left;
						comboBoxParent.Top = textBoxAddCategory.Bottom + ScaleY(3);
						buttonAdd.Top = comboBoxParent.Top + (comboBoxParent.Height - buttonAdd.Height) / 2;
						buttonAdd.Left = comboBoxParent.Right + ScaleX(3);

						if (buttonAdd.Right > textBoxAddCategory.Right)
						{
							int deltaX = buttonAdd.Right - textBoxAddCategory.Right;
							textBoxAddCategory.Width += deltaX;
							using (LayoutHelper.SuspendAnchoring(textBoxAddCategory, buttonAdd, comboBoxParent))
								panelAddCategory.Width += deltaX;
							categoryContainerControl.Width += deltaX;
						}
						else
						{
							buttonAdd.Left = textBoxAddCategory.Right - buttonAdd.Width;
							comboBoxParent.Width = buttonAdd.Left - comboBoxParent.Left - ScaleX(3);
						}

						int deltaY = comboBoxParent.Bottom - textBoxAddCategory.Bottom;
						panelAddCategory.Height += deltaY;
						categoryContainerControl.Top += deltaY;
						categoryRefreshControl.Top += deltaY;
					}
				}
				else
				{
					using (new AutoGrow(this, AnchorStyles.Right, false))
					{
						int deltaX = -buttonAdd.Width + DisplayHelper.AutoFitSystemButton(buttonAdd);
						textBoxAddCategory.Width -= deltaX;

						int desiredWidth = DisplayHelper.MeasureString(textBoxAddCategory, textBoxAddCategory.Text).Width + (int)DisplayHelper.ScaleX(10);
						deltaX += desiredWidth - textBoxAddCategory.Width;
						if (deltaX > 0)
						{
							panelAddCategory.Width += deltaX;
							categoryContainerControl.Width += deltaX;
//							textBoxAddCategory.Width += deltaX;
//							buttonAdd.Left = textBoxAddCategory.Right + ScaleX(3);
//							textBoxAddCategory.Width = Math.Max(desiredWidth, textBoxAddCategory.Width);
//							textBoxAddCategory.Width = buttonAdd.Left - textBoxAddCategory.Left - ScaleX(3);
						}
					}
				}

				/*using (LayoutHelper.SuspendAnchoring(comboBoxParent, buttonAdd, textBoxAddCategory, panelAddCategory, categoryContainerControl))
				{
					if (comboBoxParent.Visible)
					{
						deltaW = -comboBoxParent.Width + DisplayHelper.AutoFitSystemCombo(comboBoxParent, 0, int.MaxValue, true);
						buttonAdd.Left += deltaW;
					}

					int oldWidth = buttonAdd.Width;
					DisplayHelper.AutoFitSystemButton(buttonAdd);
					buttonAdd.Width += (int)DisplayHelper.ScaleX(6); // add some more "air" in the Add button
					deltaW += buttonAdd.Width - oldWidth;

					panelAddCategory.Width += deltaW;
					categoryContainerControl.Width += deltaW;
					Width += deltaW;
				}*/
			}

			// use design time defaults to drive dynamic layout
			_topMargin = categoryContainerControl.Top ;
			_bottomMargin = Bottom - categoryContainerControl.Bottom ;

			using (new AutoGrow(this, AnchorStyles.Right, false))
				LayoutControls(_categoryContext, true, false);
			UpdateSelectedCategories(_categoryContext.SelectedCategories);

			BidiHelper.RtlLayoutFixup(this);
		}

		private System.Windows.Forms.Panel panelAddCategory;
		private System.Windows.Forms.TextBox textBoxAddCategory;
		private System.Windows.Forms.Button buttonAdd;
		private OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl.CategoryRefreshControl categoryRefreshControl;
		private ParentCategoryComboBox comboBoxParent;

		protected override CreateParams CreateParams
		{
			get
			{
				CreateParams createParams = base.CreateParams;

				// Borderless windows show in the alt+tab window, so this fakes
				// out windows into thinking its a tool window (which doesn't
				// show up in the alt+tab window).
				createParams.ExStyle |= 0x00000080; // WS_EX_TOOLWINDOW

				return createParams;
			}
		}

		protected override bool ProcessCmdKey(ref Message msg, Keys keyData)
		{
			if ( keyData == Keys.Enter )
			{
				if ( textBoxAddCategory.ContainsFocus )
				{
					AddCategory() ;
					return true ;
				}
				else if ( categoryContainerControl.ContainsFocus )
				{
					Close() ;
					return true ;
				}
				else
				{
					return false ;
				}
			}

			else if (keyData == Keys.Escape )
			{
				Close();
				return true;
			}

			return base.ProcessCmdKey(ref msg, keyData);
		}

		protected override void OnPaintBackground(PaintEventArgs e)
		{
			base.OnPaintBackground(e);

            // I don't know why this is necessary, but when RightToLeft and RightToLeftLayout
            // are both true, the rightmost column or two of pixels get clipped unless we
            // explicitly reset the clip.
            e.Graphics.ResetClip();

            // draw border around form
			using ( Pen pen = new Pen(ColorizedResources.Instance.BorderDarkColor) )
				e.Graphics.DrawRectangle(pen, 0, 0, ClientSize.Width - 1, ClientSize.Height - 1);

			// draw border around category control
            Color controlBorderColor = ColorHelper.GetThemeBorderColor(ColorizedResources.Instance.BorderDarkColor) ;
			using ( Pen pen = new Pen( controlBorderColor, 1 ))
			{
				Rectangle categoryRect = categoryContainerControl.Bounds ;
				categoryRect.Inflate(1,1);
				e.Graphics.DrawRectangle(pen, categoryRect);
			}
		}

		private int _topMargin ;
		private int _bottomMargin  ;
		private Panel categoryContainerControl;

		private void LayoutControls(CategoryContext categoryContext, bool sizeForm, bool performRtlLayoutFixup)
		{
			ClearForm();
			SuspendLayout();

			// calculate how much room there is above me on the parent form
			int parentControlY = _parentControl.PointToScreen(_parentControl.Location).Y ;
			Form parentForm = _parentControl.FindForm() ;
			int parentFormY = parentForm.PointToScreen(parentForm.ClientRectangle.Location).Y ;
			int maxHeight = parentControlY - parentFormY - ScaleY(_topMargin) - ScaleY(_bottomMargin);

			// enforce additional constraint (or not, let freedom reign!)
			//maxHeight = Math.Min(maxHeight, 400) ;

			using (PositionManager positionManager = new PositionManager(ScaleX(X_MARGIN), ScaleY(Y_MARGIN + 2), ScaleY(4), ScaleX(MinDropDownWidth), categoryContainerControl.Width, maxHeight, scale))
			{
				// add 'none' if we're single selecting categories
				if (categoryContext.SelectionMode != CategoryContext.SelectionModes.MultiSelect)
					AddCategoryControl(new BlogPostCategoryListItem(new BlogPostCategoryNone(), 0), positionManager);

				// add the other categories
				BlogPostCategoryListItem[] categoryListItems = BlogPostCategoryListItem.BuildList(categoryContext.Categories, true) ;
				foreach(BlogPostCategoryListItem categoryListItem in categoryListItems)
					AddCategoryControl(categoryListItem, positionManager) ;

				if ( sizeForm )
					PositionAndSizeForm(positionManager);
			}
			if (performRtlLayoutFixup)
				BidiHelper.RtlLayoutFixup(categoryContainerControl);
			ResumeLayout();
		}

		private BlogPostCategory[] GetCategories(CategoryContext context)
		{
			ArrayList categories = new ArrayList(context.Categories);
			categories.Sort();

			return (BlogPostCategory[]) categories.ToArray(typeof (BlogPostCategory));
		}

		private void ClearForm()
		{
			if (_categoryControls.Count > 0)
			{
				categoryContainerControl.Controls.Clear();
				_categoryControls.Clear();
			}
		}

		private void AddCategoryControl(BlogPostCategoryListItem categoryListItem, PositionManager positionManager)
		{
			ICategorySelectorControl catSelector =
				CategorySelectorControlFactory.Instance.GetControl(categoryListItem.Category,
				                                                   (_categoryContext.SelectionMode ==
				                                                    CategoryContext.SelectionModes.MultiSelect));
			catSelector.SelectedChanged += new EventHandler(catSelector_SelectedChanged);

			catSelector.Control.Scale(new SizeF(scale.X, scale.Y));

			positionManager.PositionControl(catSelector.Control, categoryListItem.IndentLevel);

			categoryContainerControl.Controls.Add(catSelector.Control);

			_categoryControls.Add(catSelector.Control);
		}

		private void PositionAndSizeForm(PositionManager manager)
		{
			// determine height based on position manager calculations
			categoryContainerControl.Height = manager.Height;
			Height = manager.Height + ScaleY(_topMargin) + ScaleY(_bottomMargin) ;

			Point bottomRightCorner =
				_parentControl.PointToScreen(new Point(_parentControl.Width - Width, -Height));
			Location = bottomRightCorner;
		}

		#region High DPI Scaling
        protected override void ScaleControl(SizeF factor, BoundsSpecified specified)
        {
            SaveScaleState(factor.Width, factor.Height);
            base.ScaleControl(factor, specified);
        }

		protected override void ScaleCore(float dx, float dy)
		{
		    SaveScaleState(dx, dy);
		    base.ScaleCore(dx, dy);
		}

	    private void SaveScaleState(float dx, float dy)
	    {
	        scale = new PointF(scale.X*dx, scale.Y*dy);

	        //synchronize the comboBoxParent item height so it matches the scaled control height.
	        //Note: ScaleY(3) is padding to deal with mismatches in the way the ItemHeight scales versus its peer controls...
	        //comboBoxParent.ItemHeight = (int) (comboBoxParent.ItemHeight*dy) + ScaleY(3);
	        comboBoxParent.ItemHeight = (int) (comboBoxParent.ItemHeight*dy) + (scale.Y == 1f ? 0 : ScaleY(3));
	    }

	    private PointF scale = new PointF(1f, 1f);

		protected int ScaleX(int x)
		{
			return (int) (x*scale.X);
		}

		protected int ScaleY(int y)
		{
			return (int) (y*scale.Y);
		}
		#endregion

		private const int Y_MARGIN = 2;
		private const int X_MARGIN = 4;

		private void CommitSelection()
		{
			ArrayList selectedCategories = new ArrayList();
			foreach (ICategorySelectorControl categoryControl in _categoryControls)
			{
				if (categoryControl.Selected)
				{
					if (BlogPostCategoryNone.IsCategoryNone(categoryControl.Category))
					{
						selectedCategories.Clear();
						break;
					}
					else
					{
						selectedCategories.Add(categoryControl.Category);
					}
				}
			}
			_categoryContext.SelectedCategories = (BlogPostCategory[]) selectedCategories.ToArray(typeof (BlogPostCategory));
		}

		private BlogPostCategory[] GetCurrentlySelectedCategories()
		{
			ArrayList selectedCategories = new ArrayList();
			foreach (ICategorySelectorControl sc in _categoryControls)
			{
				if (sc.Selected)
				{
					if (BlogPostCategoryNone.IsCategoryNone(sc.Category))
					{
						selectedCategories.Clear();
						break;
					}
					else
					{
						selectedCategories.Add(sc.Category);
					}
				}
			}
			return (BlogPostCategory[]) selectedCategories.ToArray(typeof (BlogPostCategory));
		}

		private void UpdateSelectedCategories(BlogPostCategory[] selectedCategories)
		{
			bool focused = false;
			foreach (ICategorySelectorControl sc in _categoryControls)
			{
				if (!focused)
				{
					sc.Control.Focus();
					focused = true;
				}
				sc.Selected = false;
			}

			if (selectedCategories.Length > 0)
			{
				foreach (BlogPostCategory c in selectedCategories)
					foreach (ICategorySelectorControl sc in _categoryControls)
					{
						if (c.Id.ToLower(CultureInfo.CurrentCulture) == sc.Category.Id.ToLower(CultureInfo.CurrentCulture) ||
							c.Name.ToLower(CultureInfo.CurrentCulture) == sc.Category.Name.ToLower(CultureInfo.CurrentCulture) )
						{
							sc.Selected = true;
							break;
						}
					}
			}
			else
			{
				// scan for special "None" category and select it
				foreach (ICategorySelectorControl sc in _categoryControls)
				{
					if (BlogPostCategoryNone.IsCategoryNone((sc.Category)))
					{
						sc.Selected = true;
						break;
					}
				}
			}
		}

		private void textBoxAddCategory_Enter(object sender, System.EventArgs e)
		{
			if ( textBoxAddCategory.Text == Res.Get(StringId.CategoryAdd) )
				ActivateAddTextBoxForEdit()	 ;
		}

		private void textBoxAddCategory_Leave(object sender, System.EventArgs e)
		{
			if ( textBoxAddCategory.Text.Trim() == String.Empty )
				ClearAddTextBox() ;
		}

		private void ClearAddTextBox()
		{
			textBoxAddCategory.ForeColor = SystemColors.GrayText ;
			textBoxAddCategory.Text = Res.Get(StringId.CategoryAdd);
		}

		private void ActivateAddTextBoxForEdit()
		{
			textBoxAddCategory.ForeColor = SystemColors.ControlText;
			textBoxAddCategory.Text = String.Empty ;
		}

		private void buttonAdd_Click(object sender, System.EventArgs e)
		{
			AddCategory() ;
		}

		private void AddCategory()
		{
			// add the new category
			BlogPostCategory newCategory = GetNewCategory() ;

			// see if the "new" category is already in our list
			if ( newCategory != null )
			{
				ICategorySelectorControl selectorControl = GetCategorySelectorControl(newCategory) ;

				// if there is no existing selector control then add the category
				if ( selectorControl == null )
					_categoryContext.AddNewCategory(newCategory);

				// now re-lookup the selector control and select it
				selectorControl = GetCategorySelectorControl(newCategory) ;
				selectorControl.Selected = true ;

				// ensure the added category is scrolled into view
				categoryContainerControl.ScrollControlIntoView(selectorControl.Control);

				// clear the parent combo and update its ui
				comboBoxParent.SelectedIndex = 0 ;
				UpdateParentComboForeColor() ;

				// setup the text box to add another category if we support multiple categories
				if ( _categoryContext.SelectionMode == CategoryContext.SelectionModes.MultiSelect )
				{
					ActivateAddTextBoxForEdit() ;
					textBoxAddCategory.Focus() ;
				}
				else
				{
					ClearAddTextBox() ;
					selectorControl.Control.Focus() ;
				}
			}
		}

		private BlogPostCategory GetNewCategory()
		{
			if ( textBoxAddCategory.ForeColor == SystemColors.ControlText )
			{
				string categoryName = this.textBoxAddCategory.Text.Trim() ;
				if ( categoryName != String.Empty )
				{
					// see if we have a parent
					BlogPostCategory parentCategory = GetParentCategory() ;
					if ( parentCategory != null )
						return new BlogPostCategory(categoryName, categoryName, parentCategory.Id);
					else
						return new BlogPostCategory(categoryName);
				}
				else
				{
					return null ;
				}
			}
			else
			{
				return null ;
			}
		}

		private ICategorySelectorControl GetCategorySelectorControl(BlogPostCategory category)
		{
			// scan for control
			foreach (ICategorySelectorControl selectorControl in _categoryControls)
			{
				if ( selectorControl.Category.Id.ToLower(CultureInfo.CurrentCulture) == category.Id.ToLower(CultureInfo.CurrentCulture) ||
					 selectorControl.Category.Name.ToLower(CultureInfo.CurrentCulture) == category.Name.ToLower(CultureInfo.CurrentCulture) )
				{
					return selectorControl ;
				}
			}

			// didn't find it
			return null ;

		}

		#region Windows Form Designer generated code

		/// <summary>
		/// Required method for Designer support - do not modify
		/// the contents of this method with the code editor.
		/// </summary>
		private void InitializeComponent()
		{
			this.categoryContainerControl = new System.Windows.Forms.Panel();
			this.panelAddCategory = new System.Windows.Forms.Panel();
			this.comboBoxParent = new OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl.CategoryDisplayFormM1.ParentCategoryComboBox();
			this.buttonAdd = new System.Windows.Forms.Button();
			this.textBoxAddCategory = new System.Windows.Forms.TextBox();
			this.categoryRefreshControl = new OpenLiveWriter.PostEditor.PostPropertyEditing.CategoryControl.CategoryRefreshControl();
			this.panelAddCategory.SuspendLayout();
			this.SuspendLayout();
			//
			// categoryContainerControl
			//
			this.categoryContainerControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.categoryContainerControl.AutoScroll = true;
			this.categoryContainerControl.Location = new System.Drawing.Point(7, 33);
			this.categoryContainerControl.Name = "categoryContainerControl";
			this.categoryContainerControl.Size = new System.Drawing.Size(189, 72);
			this.categoryContainerControl.TabIndex = 0;
			//
			// panelAddCategory
			//
			this.panelAddCategory.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.panelAddCategory.Controls.Add(this.comboBoxParent);
			this.panelAddCategory.Controls.Add(this.buttonAdd);
			this.panelAddCategory.Controls.Add(this.textBoxAddCategory);
			this.panelAddCategory.Location = new System.Drawing.Point(6, 5);
			this.panelAddCategory.Name = "panelAddCategory";
			this.panelAddCategory.Size = new System.Drawing.Size(194, 25);
			this.panelAddCategory.TabIndex = 1;
			//
			// comboBoxParent
			//
			this.comboBoxParent.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.comboBoxParent.DrawMode = System.Windows.Forms.DrawMode.OwnerDrawFixed;
			this.comboBoxParent.DropDownStyle = System.Windows.Forms.ComboBoxStyle.DropDownList;
			this.comboBoxParent.DropDownWidth = 200;
			this.comboBoxParent.IntegralHeight = false;
			this.comboBoxParent.ItemHeight = 15;
			this.comboBoxParent.Location = new System.Drawing.Point(42, 1);
			this.comboBoxParent.MaxDropDownItems = 20;
			this.comboBoxParent.Name = "comboBoxParent";
			this.comboBoxParent.Size = new System.Drawing.Size(88, 21);
			this.comboBoxParent.TabIndex = 1;
			this.comboBoxParent.Leave += new System.EventHandler(this.comboBoxParent_Leave);
			this.comboBoxParent.Enter += new System.EventHandler(this.comboBoxParent_Enter);
			//
			// buttonAdd
			//
			this.buttonAdd.Anchor = ((System.Windows.Forms.AnchorStyles)((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Right)));
			this.buttonAdd.FlatStyle = System.Windows.Forms.FlatStyle.System;
			this.buttonAdd.Location = new System.Drawing.Point(134, 0);
			this.buttonAdd.Name = "buttonAdd";
			this.buttonAdd.Size = new System.Drawing.Size(59, 23);
			this.buttonAdd.TabIndex = 2;
			this.buttonAdd.Text = "&Add";
			this.buttonAdd.Click += new System.EventHandler(this.buttonAdd_Click);
			//
			// textBoxAddCategory
			//
			this.textBoxAddCategory.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Top | System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.textBoxAddCategory.AutoSize = false;
			this.textBoxAddCategory.Location = new System.Drawing.Point(0, 1);
			this.textBoxAddCategory.Name = "textBoxAddCategory";
			this.textBoxAddCategory.Size = new System.Drawing.Size(38, 21);
			this.textBoxAddCategory.TabIndex = 0;
			this.textBoxAddCategory.Text = "";
			this.textBoxAddCategory.Leave += new System.EventHandler(this.textBoxAddCategory_Leave);
			this.textBoxAddCategory.Enter += new System.EventHandler(this.textBoxAddCategory_Enter);
			//
			// categoryRefreshControl
			//
			this.categoryRefreshControl.Anchor = ((System.Windows.Forms.AnchorStyles)(((System.Windows.Forms.AnchorStyles.Bottom | System.Windows.Forms.AnchorStyles.Left)
				| System.Windows.Forms.AnchorStyles.Right)));
			this.categoryRefreshControl.BackColor = System.Drawing.SystemColors.ControlLightLight;
			this.categoryRefreshControl.Location = new System.Drawing.Point(6, 111);
			this.categoryRefreshControl.Name = "categoryRefreshControl";
			this.categoryRefreshControl.Size = new System.Drawing.Size(193, 23);
			this.categoryRefreshControl.TabIndex = 2;
			//
			// CategoryDisplayFormM1
			//
			this.AutoScaleBaseSize = new System.Drawing.Size(5, 14);
			this.AutoScrollMargin = new System.Drawing.Size(2, 2);
			this.BackColor = System.Drawing.SystemColors.ControlLightLight;
			this.ClientSize = new System.Drawing.Size(205, 138);
			this.ControlBox = false;
			this.Controls.Add(this.categoryRefreshControl);
			this.Controls.Add(this.panelAddCategory);
			this.Controls.Add(this.categoryContainerControl);
			this.DismissOnDeactivate = true;
			this.DockPadding.All = 1;
			this.MaximizeBox = false;
			this.MinimizeBox = false;
			this.Name = "CategoryDisplayFormM1";
			this.SizeGripStyle = System.Windows.Forms.SizeGripStyle.Hide;
			this.panelAddCategory.ResumeLayout(false);
			this.ResumeLayout(false);

		}

		#endregion

		/// <summary>
		/// Clean up any resources being used.
		/// </summary>
		protected override void Dispose(bool disposing)
		{
			if (disposing)
			{
				_categoryContext.Changed -= new CategoryContext.CategoryChangedEventHandler(_categoryContext_Changed);
				if (components != null)
				{
					components.Dispose();
				}
			}
			base.Dispose(disposing);
		}

		private System.ComponentModel.IContainer components = new Container();
		private ArrayList _categoryControls = new ArrayList();
		private CategoryContext _categoryContext;
		private Control _parentControl;

		private void catSelector_SelectedChanged(object sender, EventArgs e)
		{
			CommitSelection();
		}

		private void _categoryContext_Changed(object sender, CategoryContext.CategoryChangedEventArgs e)
		{
			if (e.ChangeType == CategoryContext.ChangeType.Category || e.ChangeType == CategoryContext.ChangeType.SelectionMode)
			{
				BlogPostCategory[] selectedCategories = GetCurrentlySelectedCategories();
				LayoutControls(_categoryContext, false, true);
				UpdateSelectedCategories(selectedCategories);
				RefreshParentCombo() ;
				Invalidate() ;
			}
		}

		private void RefreshParentCombo()
		{
			// populate "parent" combo
			object selectedItem = comboBoxParent.SelectedItem ;
			comboBoxParent.Items.Clear();
			comboBoxParent.Items.Add(new ParentCategoryComboItemNone(comboBoxParent)) ;
			BlogPostCategoryListItem[] categoryListItems = BlogPostCategoryListItem.BuildList(_categoryContext.BlogCategories, true) ;
			foreach(BlogPostCategoryListItem categoryListItem in categoryListItems)
				comboBoxParent.Items.Add(new ParentCategoryComboItem(comboBoxParent, categoryListItem.Category, categoryListItem.IndentLevel)) ;
			UpdateParentComboForeColor() ;
			if ( selectedItem != null && comboBoxParent.Items.Contains(selectedItem))
				comboBoxParent.SelectedItem = selectedItem ;
			else
				comboBoxParent.SelectedIndex = 0 ;
		}

		private BlogPostCategory GetParentCategory()
		{
			ParentCategoryComboItem parentComboItem = comboBoxParent.SelectedItem as ParentCategoryComboItem ;
			if ( parentComboItem != null )
			{
				if ( !BlogPostCategoryNone.IsCategoryNone(parentComboItem.Category) )
					return parentComboItem.Category ;
				else
					return null ;
			}
			else
			{
				return null ;
			}
		}

		private void comboBoxParent_Enter(object sender, System.EventArgs e)
		{
			comboBoxParent.ForeColor = SystemColors.ControlText;
		}

		private void comboBoxParent_Leave(object sender, System.EventArgs e)
		{
			UpdateParentComboForeColor() ;
		}

		private void UpdateParentComboForeColor()
		{
			if ( GetParentCategory() != null )
				comboBoxParent.ForeColor = SystemColors.ControlText ;
			else
				comboBoxParent.ForeColor = SystemColors.GrayText ;
		}

		private class ParentCategoryComboItem
		{
			public ParentCategoryComboItem(ComboBox parentCombo, BlogPostCategory category, int indentLevel)
			{
				_parentCombo = parentCombo ;
				_category = category ;
				_indentLevel = indentLevel ;
			}

			public BlogPostCategory Category
			{
				get { return _category; }
			}
			private BlogPostCategory _category ;

			public override bool Equals(object obj)
			{
				return (obj as ParentCategoryComboItem).Category.Equals(Category) ;
			}

			public override int GetHashCode()
			{
				return Category.GetHashCode() ;
			}

			public override string ToString()
			{
				// default padding
				string padding = new String(' ', _indentLevel * 3) ;

				// override if we are selected
				if ( !_parentCombo.DroppedDown && (_parentCombo.SelectedItem != null) && this.Equals(_parentCombo.SelectedItem) )
					padding = String.Empty ;

				string categoryName = HtmlUtils.UnEscapeEntities(Category.Name, HtmlUtils.UnEscapeMode.Default) ;
				string stringRepresentation = String.Format(CultureInfo.InvariantCulture, "{0}{1}", padding, categoryName) ;
				return stringRepresentation ;
			}

			private int _indentLevel ;
			private ComboBox _parentCombo ;

		}

		private class ParentCategoryComboBox : ComboBox
		{
			public ParentCategoryComboBox()
			{
				// prevent editing and showing of drop down
				DropDownStyle = ComboBoxStyle.DropDownList ;

				// fully cusotm painting
				DrawMode = DrawMode.OwnerDrawFixed ;
				IntegralHeight = false ;
			}

			protected override void OnDrawItem(DrawItemEventArgs e)
			{
				if (e.Index != -1)
				{
					ParentCategoryComboItem comboItem = Items[e.Index] as ParentCategoryComboItem ;

					e.DrawBackground();

					// don't indent for main display of category
					string text = comboItem.ToString();
					if  (e.Bounds.Width < Width)
						text = text.Trim() ;

					using ( Brush brush = new SolidBrush(e.ForeColor) )
						e.Graphics.DrawString(text, e.Font, brush, e.Bounds.X, e.Bounds.Y) ;

					e.DrawFocusRectangle();
				}
			}
		}

		private class ParentCategoryComboItemNone : ParentCategoryComboItem
		{
			public ParentCategoryComboItemNone(ComboBox parentCombo)
				: base(parentCombo, new BlogPostCategoryNone(), 0)
			{
			}

			public override string ToString()
			{
				return Res.Get(StringId.CategoryNoParent) ;
			}
		}

		private class PositionManager : IDisposable
		{
			private int _top;
			private int _left;
			private int _width;
			private int _margin;
			private ArrayList _controls = new ArrayList();
			private int _maxWidth;
			private int _minWidth;
			private int _maxHeight ;
			private int _enforcedMaxHeight = -1 ;
			private PointF _autoScaleSize;
			private StringFormat _format;

			public PositionManager(int initialLeft, int initialTop, int scaledMargin, int minWidth, int maxWidth, int maxHeight, PointF autoScaleSize)
			{
				_left = initialLeft;
				_top = initialTop;
				_margin = scaledMargin;
				_maxWidth = maxWidth;
				_minWidth = _width = minWidth;
				_maxHeight = maxHeight ;
				_autoScaleSize = autoScaleSize;
				_format = new StringFormat();
				_format.Trimming = StringTrimming.EllipsisCharacter;
			}

			public void PositionControl(Control c, int indentLevel)
			{
				int INDENT_MARGIN = ScaleX(16) ;
				c.Top = _top;
				c.Left = _left + (INDENT_MARGIN * indentLevel);

				Graphics g = c.CreateGraphics();
				try
				{
					int maxWidth = _maxWidth - SystemInformation.VerticalScrollBarWidth - c.Left - _left;
					c.Width = maxWidth;
					if (c is CheckBox)
						DisplayHelper.AutoFitSystemCheckBox((CheckBox)c, 0, maxWidth);
					else if (c is RadioButton)
						DisplayHelper.AutoFitSystemRadioButton((RadioButton)c, 0, maxWidth);
					else
						Debug.Fail("Being asked to position a control that isn't a radiobutton or checkbox");
					LayoutHelper.NaturalizeHeight(c);
				}
				finally
				{
					g.Dispose();
				}
				_width = Math.Max(_width, c.Width);
				_controls.Add(c);

				_top = _top + c.Height + _margin;

				// enforce max height if necessary
				if ( _enforcedMaxHeight == -1 && _top > _maxHeight )
					_enforcedMaxHeight = _top  ;
			}

			public int Width
			{
				get { return _width; }
			}

			public int Height
			{
				get
				{
					if ( _enforcedMaxHeight != -1 )
						return _enforcedMaxHeight ;
					else
						return _top + _margin;
				}
			}

			protected int ScaleX(int x)
			{
				return (int) (x*_autoScaleSize.X);
			}

			protected int ScaleY(int y)
			{
				return (int) (y*_autoScaleSize.Y);
			}

			#region IDisposable Members

			public void Dispose()
			{
			}

			#endregion
		}

	}
}


text:
package com.robin.webui.config;

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.support.ResourceBundleMessageSource;
import org.springframework.web.servlet.LocaleResolver;
import org.springframework.web.servlet.i18n.SessionLocaleResolver;

import java.util.Locale;

public class I18nConfig {
    @Bean
    public LocaleResolver localeResolver() {
        SessionLocaleResolver resolver = new SessionLocaleResolver();
        resolver.setDefaultLocale(Locale.getDefault());
        return resolver;
    }

    @Bean
    public ResourceBundleMessageSource resourceBundleMessageSource() {
        ResourceBundleMessageSource source = new ResourceBundleMessageSource();
        source.setBasename("i18n/messages");
        source.setDefaultEncoding("UTF-8");
        source.setUseCodeAsDefaultMessage(true);
        return source;
    }

}


text:
layout: example.html
title: Layer Z-Index
shortdesc: Example of ordering layers using Z-index.
docs: >
  There are are two managed layers (square and triangle) and one unmanaged layer (star).

  The Z-index determines the rendering order; with {square: 1, triangle: 0, star: unmanaged} indices, the rendering order is triangle, square and star on top.

tags: "layer, ordering, z-index"
---

    <input type="number" id="idx1"></input>
    Square layer Z-index

    <input type="number" id="idx2"></input>
    Triangle layer Z-index


text:
/**
 * @file    DoglegOptimizer.h
 * @brief   Unit tests for DoglegOptimizer
 * @author  Richard Roberts
 */

#include <CppUnitLite/TestHarness.h>

#include <tests/smallExample.h>
#include <gtsam/nonlinear/DoglegOptimizerImpl.h>
#include <gtsam/inference/Symbol.h>
#include <gtsam/linear/JacobianFactor.h>
#include <gtsam/linear/GaussianBayesTree.h>
#include <gtsam/base/numericalDerivative.h>

#ifdef __GNUC__
#pragma GCC diagnostic push
#pragma GCC diagnostic ignored "-Wunused-variable"
#endif
#include <boost/bind.hpp>
#ifdef __GNUC__
#pragma GCC diagnostic pop
#endif
#include <boost/assign/list_of.hpp> // for 'list_of()'
#include <functional>
#include <boost/iterator/counting_iterator.hpp>

using namespace std;
using namespace gtsam;

// Convenience for named keys
using symbol_shorthand::X;
using symbol_shorthand::L;

/* ************************************************************************* */
TEST(DoglegOptimizer, ComputeBlend) {
  // Create an arbitrary Bayes Net
  GaussianBayesNet gbn;
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      0, (Vector(2) << 1.0,2.0), (Matrix(2, 2) << 3.0,4.0,0.0,6.0),
      3, (Matrix(2, 2) << 7.0,8.0,9.0,10.0),
      4, (Matrix(2, 2) << 11.0,12.0,13.0,14.0)));
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      1, (Vector(2) << 15.0,16.0), (Matrix(2, 2) << 17.0,18.0,0.0,20.0),
      2, (Matrix(2, 2) << 21.0,22.0,23.0,24.0),
      4, (Matrix(2, 2) << 25.0,26.0,27.0,28.0)));
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      2, (Vector(2) << 29.0,30.0), (Matrix(2, 2) << 31.0,32.0,0.0,34.0),
      3, (Matrix(2, 2) << 35.0,36.0,37.0,38.0)));
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      3, (Vector(2) << 39.0,40.0), (Matrix(2, 2) << 41.0,42.0,0.0,44.0),
      4, (Matrix(2, 2) << 45.0,46.0,47.0,48.0)));
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      4, (Vector(2) << 49.0,50.0), (Matrix(2, 2) << 51.0,52.0,0.0,54.0)));

  // Compute steepest descent point
  VectorValues xu = gbn.optimizeGradientSearch();

  // Compute Newton's method point
  VectorValues xn = gbn.optimize();

  // The Newton's method point should be more "adventurous", i.e. larger, than the steepest descent point
  EXPECT(xu.vector().norm() < xn.vector().norm());

  // Compute blend
  double Delta = 1.5;
  VectorValues xb = DoglegOptimizerImpl::ComputeBlend(Delta, xu, xn);
  DOUBLES_EQUAL(Delta, xb.vector().norm(), 1e-10);
}

/* ************************************************************************* */
TEST(DoglegOptimizer, ComputeDoglegPoint) {
  // Create an arbitrary Bayes Net
  GaussianBayesNet gbn;
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      0, (Vector(2) << 1.0,2.0), (Matrix(2, 2) << 3.0,4.0,0.0,6.0),
      3, (Matrix(2, 2) << 7.0,8.0,9.0,10.0),
      4, (Matrix(2, 2) << 11.0,12.0,13.0,14.0)));
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      1, (Vector(2) << 15.0,16.0), (Matrix(2, 2) << 17.0,18.0,0.0,20.0),
      2, (Matrix(2, 2) << 21.0,22.0,23.0,24.0),
      4, (Matrix(2, 2) << 25.0,26.0,27.0,28.0)));
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      2, (Vector(2) << 29.0,30.0), (Matrix(2, 2) << 31.0,32.0,0.0,34.0),
      3, (Matrix(2, 2) << 35.0,36.0,37.0,38.0)));
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      3, (Vector(2) << 39.0,40.0), (Matrix(2, 2) << 41.0,42.0,0.0,44.0),
      4, (Matrix(2, 2) << 45.0,46.0,47.0,48.0)));
  gbn += GaussianConditional::shared_ptr(new GaussianConditional(
      4, (Vector(2) << 49.0,50.0), (Matrix(2, 2) << 51.0,52.0,0.0,54.0)));

  // Compute dogleg point for different deltas

  double Delta1 = 0.5;  // Less than steepest descent
  VectorValues actual1 = DoglegOptimizerImpl::ComputeDoglegPoint(Delta1, gbn.optimizeGradientSearch(), gbn.optimize());
  DOUBLES_EQUAL(Delta1, actual1.vector().norm(), 1e-5);

  double Delta2 = 1.5;  // Between steepest descent and Newton's method
  VectorValues expected2 = DoglegOptimizerImpl::ComputeBlend(Delta2, gbn.optimizeGradientSearch(), gbn.optimize());
  VectorValues actual2 = DoglegOptimizerImpl::ComputeDoglegPoint(Delta2, gbn.optimizeGradientSearch(), gbn.optimize());
  DOUBLES_EQUAL(Delta2, actual2.vector().norm(), 1e-5);
  EXPECT(assert_equal(expected2, actual2));

  double Delta3 = 5.0;  // Larger than Newton's method point
  VectorValues expected3 = gbn.optimize();
  VectorValues actual3 = DoglegOptimizerImpl::ComputeDoglegPoint(Delta3, gbn.optimizeGradientSearch(), gbn.optimize());
  EXPECT(assert_equal(expected3, actual3));
}

/* ************************************************************************* */
TEST(DoglegOptimizer, Iterate) {
  // really non-linear factor graph
  NonlinearFactorGraph fg = example::createReallyNonlinearFactorGraph();

  // config far from minimum
  Point2 x0(3,0);
  Values config;
  config.insert(X(1), x0);

  double Delta = 1.0;
  for(size_t it=0; it<10; ++it) {
    GaussianBayesNet gbn = *fg.linearize(config)->eliminateSequential();
    // Iterate assumes that linear error = nonlinear error at the linearization point, and this should be true
    double nonlinearError = fg.error(config);
    double linearError = GaussianFactorGraph(gbn).error(config.zeroVectors());
    DOUBLES_EQUAL(nonlinearError, linearError, 1e-5);
//    cout << "it " << it << ", Delta = " << Delta << ", error = " << fg->error(*config) << endl;
    VectorValues dx_u = gbn.optimizeGradientSearch();
    VectorValues dx_n = gbn.optimize();
    DoglegOptimizerImpl::IterationResult result = DoglegOptimizerImpl::Iterate(Delta, DoglegOptimizerImpl::SEARCH_EACH_ITERATION, dx_u, dx_n, gbn, fg, config, fg.error(config));
    Delta = result.Delta;
    EXPECT(result.f_error < fg.error(config)); // Check that error decreases
    Values newConfig(config.retract(result.dx_d));
    config = newConfig;
    DOUBLES_EQUAL(fg.error(config), result.f_error, 1e-5); // Check that error is correctly filled in
  }
}

/* ************************************************************************* */
int main() { TestResult tr; return TestRegistry::runAllTests(tr); }
/* ************************************************************************* */


text:
from __future__ import absolute_import

import pytest
import re
import responses
import six
from symbolic import SourceMapTokenMatch

from mock import patch
from requests.exceptions import RequestException

from sentry import http
from sentry.lang.javascript.processor import (
    JavaScriptStacktraceProcessor,
    discover_sourcemap,
    fetch_sourcemap,
    fetch_file,
    generate_module,
    trim_line,
    fetch_release_file,
    UnparseableSourcemap,
    get_max_age,
    CACHE_CONTROL_MAX,
    CACHE_CONTROL_MIN,
)
from sentry.lang.javascript.errormapping import (rewrite_exception, REACT_MAPPING_URL)
from sentry.models import File, Release, ReleaseFile, EventError
from sentry.testutils import TestCase
from sentry.utils.strings import truncatechars

base64_sourcemap = 'data:application/json;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiZ2VuZXJhdGVkLmpzIiwic291cmNlcyI6WyIvdGVzdC5qcyJdLCJuYW1lcyI6W10sIm1hcHBpbmdzIjoiO0FBQUEiLCJzb3VyY2VzQ29udGVudCI6WyJjb25zb2xlLmxvZyhcImhlbGxvLCBXb3JsZCFcIikiXX0='

unicode_body = b"""function add(a, b) {
    "use strict";
    return a + b; // f\xc3\xb4o
}""".decode('utf-8')

class JavaScriptStacktraceProcessorTest(TestCase):
    def test_infers_allow_scraping(self):
        project = self.create_project()
        r = JavaScriptStacktraceProcessor({}, None, project)
        # defaults
        assert r.allow_scraping

        # disabled for project
        project.update_option('sentry:scrape_javascript', False)
        r = JavaScriptStacktraceProcessor({}, None, project)
        assert not r.allow_scraping

        # disabled for org
        project.delete_option('sentry:scrape_javascript')
        project.organization.update_option('sentry:scrape_javascript', False)
        r = JavaScriptStacktraceProcessor({}, None, project)
        assert not r.allow_scraping

class FetchReleaseFileTest(TestCase):
    def test_unicode(self):
        project = self.project
        release = Release.objects.create(
            organization_id=project.organization_id,
            version='abc',
        )
        release.add_project(project)

        file = File.objects.create(
            name='file.min.js',
            type='release.file',
            headers={'Content-Type': 'application/json; charset=utf-8'},
        )

        binary_body = unicode_body.encode('utf-8')
        file.putfile(six.BytesIO(binary_body))

        ReleaseFile.objects.create(
            name='file.min.js',
            release=release,
            organization_id=project.organization_id,
            file=file,
        )

        result = fetch_release_file('file.min.js', release)

        assert isinstance(result.body, six.binary_type)
        assert result == http.UrlResult(
            'file.min.js',
            {'content-type': 'application/json; charset=utf-8'},
            binary_body,
            200,
            'utf-8',
        )

        # test with cache hit, which should be compressed
        new_result = fetch_release_file('file.min.js', release)

        assert result == new_result

    def test_distribution(self):
        project = self.project
        release = Release.objects.create(
            organization_id=project.organization_id,
            version='abc',
        )
        release.add_project(project)

        other_file = File.objects.create(
            name='file.min.js',
            type='release.file',
            headers={'Content-Type': 'application/json; charset=utf-8'},
        )
        file = File.objects.create(
            name='file.min.js',
            type='release.file',
            headers={'Content-Type': 'application/json; charset=utf-8'},
        )

        binary_body = unicode_body.encode('utf-8')
        other_file.putfile(six.BytesIO(b''))
        file.putfile(six.BytesIO(binary_body))

        dist = release.add_dist('foo')

        ReleaseFile.objects.create(
            name='file.min.js',
            release=release,
            organization_id=project.organization_id,
            file=other_file,
        )

        ReleaseFile.objects.create(
            name='file.min.js',
            release=release,
            dist=dist,
            organization_id=project.organization_id,
            file=file,
        )

        result = fetch_release_file('file.min.js', release, dist)

        assert isinstance(result.body, six.binary_type)
        assert result == http.UrlResult(
            'file.min.js',
            {'content-type': 'application/json; charset=utf-8'},
            binary_body,
            200,
            'utf-8',
        )

        # test with cache hit, which should be compressed
        new_result = fetch_release_file('file.min.js', release, dist)

        assert result == new_result

    def test_fallbacks(self):
        project = self.project
        release = Release.objects.create(
            organization_id=project.organization_id,
            version='abc',
        )
        release.add_project(project)

        file = File.objects.create(
            name='~/file.min.js',
            type='release.file',
            headers={'Content-Type': 'application/json; charset=utf-8'},
        )

        binary_body = unicode_body.encode('utf-8')
        file.putfile(six.BytesIO(binary_body))

        ReleaseFile.objects.create(
            name='~/file.min.js',
            release=release,
            organization_id=project.organization_id,
            file=file,
        )

        result = fetch_release_file('http://example.com/file.min.js?lol', release)

        assert isinstance(result.body, six.binary_type)
        assert result == http.UrlResult(
            'http://example.com/file.min.js?lol',
            {'content-type': 'application/json; charset=utf-8'},
            binary_body,
            200,
            'utf-8',
        )

class FetchFileTest(TestCase):
    @responses.activate
    def test_simple(self):
        responses.add(
            responses.GET, 'http://example.com', body='foo bar', content_type='application/json'
        )

        result = fetch_file('http://example.com')

        assert len(responses.calls) == 1

        assert result.url == 'http://example.com'
        assert result.body == 'foo bar'
        assert result.headers == {'content-type': 'application/json'}

        # ensure we use the cached result
        result2 = fetch_file('http://example.com')

        assert len(responses.calls) == 1

        assert result == result2

    @responses.activate
    def test_with_token(self):
        responses.add(
            responses.GET,
            re.compile(r'http://example.com/\d+/'),
            body='foo bar',
            content_type='application/json'
        )

        self.project.update_option('sentry:token', 'foobar')
        self.project.update_option('sentry:origins', ['*'])

        default_header_name = 'X-Sentry-Token'
        header_pairs = [
            (None, default_header_name),
            ('', default_header_name),
            ('X-Custom-Token-Header', 'X-Custom-Token-Header'),
        ]

        for i, (header_name_option_value, expected_request_header_name) in enumerate(header_pairs):
            self.project.update_option('sentry:token_header', header_name_option_value)

            url = 'http://example.com/{}/'.format(i)
            result = fetch_file(url, project=self.project)

            assert result.url == url
            assert result.body == 'foo bar'
            assert result.headers == {'content-type': 'application/json'}

            assert len(responses.calls) == i + 1
            assert responses.calls[i].request.headers[expected_request_header_name] == 'foobar'

    @responses.activate
    def test_connection_failure(self):
        responses.add(responses.GET, 'http://example.com', body=RequestException())

        with pytest.raises(http.BadSource):
            fetch_file('http://example.com')

        assert len(responses.calls) == 1

        # ensure we use the cached domain-wide failure for the second call
        with pytest.raises(http.BadSource):
            fetch_file('http://example.com/foo/bar')

        assert len(responses.calls) == 1

    @responses.activate
    def test_non_url_without_release(self):
        with pytest.raises(http.BadSource):
            fetch_file('/example.js')

    @responses.activate
    @patch('sentry.lang.javascript.processor.fetch_release_file')
    def test_non_url_with_release(self, mock_fetch_release_file):
        mock_fetch_release_file.return_value = http.UrlResult(
            '/example.js',
            {'content-type': 'application/json'},
            'foo',
            200,
            None,
        )

        release = Release.objects.create(version='1', organization_id=self.project.organization_id)
        release.add_project(self.project)

        result = fetch_file('/example.js', release=release)
        assert result.url == '/example.js'
        assert result.body == 'foo'
        assert isinstance(result.body, six.binary_type)
        assert result.headers == {'content-type': 'application/json'}
        assert result.encoding is None

    @responses.activate
    def test_unicode_body(self):
        responses.add(
            responses.GET,
            'http://example.com',
            body=b'"f\xc3\xb4o bar"'.decode('utf-8'),
            content_type='application/json; charset=utf-8'
        )

        result = fetch_file('http://example.com')

        assert len(responses.calls) == 1

        assert result.url == 'http://example.com'
        assert result.body == '"f\xc3\xb4o bar"'
        assert result.headers == {'content-type': 'application/json; charset=utf-8'}
        assert result.encoding == 'utf-8'

        # ensure we use the cached result
        result2 = fetch_file('http://example.com')

        assert len(responses.calls) == 1

        assert result == result2

    @responses.activate
    def test_truncated(self):
        url = truncatechars('http://example.com', 3)
        with pytest.raises(http.CannotFetch) as exc:
            fetch_file(url)

        assert exc.value.data['type'] == EventError.JS_MISSING_SOURCE
        assert exc.value.data['url'] == url

class CacheControlTest(TestCase):
    def test_simple(self):
        headers = {'content-type': 'application/json', 'cache-control': 'max-age=120'}
        assert get_max_age(headers) == 120

    def test_max_and_min(self):
        headers = {'content-type': 'application/json',
                   'cache-control': 'max-age=%s' % CACHE_CONTROL_MAX}
        assert get_max_age(headers) == CACHE_CONTROL_MAX

        headers = {'content-type': 'application/json',
                   'cache-control': 'max-age=%s' % CACHE_CONTROL_MIN}
        assert get_max_age(headers) == CACHE_CONTROL_MIN

    def test_out_of_bounds(self):
        greater_than_max = CACHE_CONTROL_MAX + 1
        headers = {'content-type': 'application/json',
                   'cache-control': 'max-age=%s' % greater_than_max}
        assert get_max_age(headers) == CACHE_CONTROL_MAX

        less_than_min = CACHE_CONTROL_MIN - 1
        headers = {'content-type': 'application/json',
                   'cache-control': 'max-age=%s' % less_than_min}
        assert get_max_age(headers) == CACHE_CONTROL_MIN

    def test_no_cache_control(self):
        headers = {'content-type': 'application/json'}
        assert get_max_age(headers) == CACHE_CONTROL_MIN

    def test_additional_cache_control_values(self):
        headers = {'content-type': 'application/json',
                   'cache-control': 'private, s-maxage=60, max-age=120'}
        assert get_max_age(headers) == 120

    def test_valid_input(self):
        headers = {'content-type': 'application/json', 'cache-control': 'max-age=12df0sdgfjhdgf'}
        assert get_max_age(headers) == CACHE_CONTROL_MIN

        headers = {'content-type': 'application/json', 'cache-control': 'max-age=df0sdgfjhdgf'}
        assert get_max_age(headers) == CACHE_CONTROL_MIN

class DiscoverSourcemapTest(TestCase):
    # discover_sourcemap(result)
    def test_simple(self):
        result = http.UrlResult('http://example.com', {}, '', 200, None)
        assert discover_sourcemap(result) is None

        result = http.UrlResult(
            'http://example.com', {'x-sourcemap': 'http://example.com/source.map.js'}, '', 200, None
        )
        assert discover_sourcemap(result) == 'http://example.com/source.map.js'

        result = http.UrlResult(
            'http://example.com', {'sourcemap': 'http://example.com/source.map.js'}, '', 200, None
        )
        assert discover_sourcemap(result) == 'http://example.com/source.map.js'

        result = http.UrlResult(
            'http://example.com', {},
            '//@ sourceMappingURL=http://example.com/source.map.js\nconsole.log(true)', 200, None
        )
        assert discover_sourcemap(result) == 'http://example.com/source.map.js'

        result = http.UrlResult(
            'http://example.com', {},
            '//# sourceMappingURL=http://example.com/source.map.js\nconsole.log(true)', 200, None
        )
        assert discover_sourcemap(result) == 'http://example.com/source.map.js'

        result = http.UrlResult(
            'http://example.com', {},
            'console.log(true)\n//@ sourceMappingURL=http://example.com/source.map.js', 200, None
        )
        assert discover_sourcemap(result) == 'http://example.com/source.map.js'

        result = http.UrlResult(
            'http://example.com', {},
            'console.log(true)\n//# sourceMappingURL=http://example.com/source.map.js', 200, None
        )
        assert discover_sourcemap(result) == 'http://example.com/source.map.js'

        result = http.UrlResult(
            'http://example.com', {},
            'console.log(true)\n//# sourceMappingURL=http://example.com/source.map.js\n//# sourceMappingURL=http://example.com/source2.map.js',
            200, None
        )
        assert discover_sourcemap(result) == 'http://example.com/source2.map.js'

        # sourceMappingURL found directly after code w/o newline
        result = http.UrlResult(
            'http://example.com', {},
            'console.log(true);//# sourceMappingURL=http://example.com/source.map.js', 200, None
        )
        assert discover_sourcemap(result) == 'http://example.com/source.map.js'

        result = http.UrlResult(
            'http://example.com', {}, '//# sourceMappingURL=app.map.js/*ascii:lol*/', 200, None
        )
        assert discover_sourcemap(result) == 'http://example.com/app.map.js'

        result = http.UrlResult('http://example.com', {}, '//# sourceMappingURL=/*lol*/', 200, None)
        with self.assertRaises(AssertionError):
            discover_sourcemap(result)

class GenerateModuleTest(TestCase):
    def test_simple(self):
        assert generate_module(None) == '<unknown module>'
        assert generate_module('http://example.com/foo.js') == 'foo'
        assert generate_module('http://example.com/foo/bar.js') == 'foo/bar'
        assert generate_module('http://example.com/js/foo/bar.js') == 'foo/bar'
        assert generate_module('http://example.com/javascript/foo/bar.js') == 'foo/bar'
        assert generate_module('http://example.com/1.0/foo/bar.js') == 'foo/bar'
        assert generate_module('http://example.com/v1/foo/bar.js') == 'foo/bar'
        assert generate_module('http://example.com/v1.0.0/foo/bar.js') == 'foo/bar'
        assert generate_module('http://example.com/_baz/foo/bar.js') == 'foo/bar'
        assert generate_module('http://example.com/1/2/3/foo/bar.js') == 'foo/bar'
        assert generate_module('http://example.com/abcdef0/foo/bar.js') == 'foo/bar'
        assert generate_module(
            'http://example.com/92cd589eca8235e7b373bf5ae94ebf898e3b949c/foo/bar.js'
        ) == 'foo/bar'
        assert generate_module(
            'http://example.com/7d6d00eae0ceccdc7ee689659585d95f/foo/bar.js'
        ) == 'foo/bar'
        assert generate_module('http://example.com/foo/bar.coffee') == 'foo/bar'
        assert generate_module('http://example.com/foo/bar.js?v=1234') == 'foo/bar'
        assert generate_module('/foo/bar.js') == 'foo/bar'
        assert generate_module('/foo/bar.ts') == 'foo/bar'
        assert generate_module('../../foo/bar.js') == 'foo/bar'
        assert generate_module('../../foo/bar.ts') == 'foo/bar'
        assert generate_module('../../foo/bar.awesome') == 'foo/bar'
        assert generate_module('../../foo/bar') == 'foo/bar'
        assert generate_module('/foo/bar-7d6d00eae0ceccdc7ee689659585d95f.js') == 'foo/bar'
        assert generate_module('/bower_components/foo/bar.js') == 'foo/bar'
        assert generate_module('/node_modules/foo/bar.js') == 'foo/bar'
        assert generate_module(
            'http://example.com/vendor.92cd589eca8235e7b373bf5ae94ebf898e3b949c.js'
        ) == 'vendor'
        assert generate_module(
            '/a/javascripts/application-bundle-149360d3414c26adac3febdf6832e25c.min.js'
        ) == 'a/javascripts/application-bundle'
        assert generate_module('https://example.com/libs/libs-20150417171659.min.js') == 'libs/libs'
        assert generate_module(
            'webpack:///92cd589eca8235e7b373bf5ae94ebf898e3b949c/vendor.js'
        ) == 'vendor'
        assert generate_module(
            'webpack:///92cd589eca8235e7b373bf5ae94ebf898e3b949c/vendor.js'
        ) == 'vendor'
        assert generate_module(
            'app:///92cd589eca8235e7b373bf5ae94ebf898e3b949c/vendor.js'
        ) == 'vendor'
        assert generate_module(
            'app:///example/92cd589eca8235e7b373bf5ae94ebf898e3b949c/vendor.js'
        ) == 'vendor'
        assert generate_module(
            '~/app/components/projectHeader/projectSelector.jsx'
        ) == 'app/components/projectHeader/projectSelector'

class FetchSourcemapTest(TestCase):
    def test_simple_base64(self):
        smap_view = fetch_sourcemap(base64_sourcemap)
        tokens = [SourceMapTokenMatch(0, 0, 1, 0, src='/test.js', src_id=0)]

        assert list(smap_view) == tokens
        sv = smap_view.get_sourceview(0)
        assert sv.get_source() == u'console.log("hello, World!")'
        assert smap_view.get_source_name(0) == u'/test.js'

    def test_base64_without_padding(self):
        smap_view = fetch_sourcemap(base64_sourcemap.rstrip('='))
        tokens = [SourceMapTokenMatch(0, 0, 1, 0, src='/test.js', src_id=0)]

        assert list(smap_view) == tokens
        sv = smap_view.get_sourceview(0)
        assert sv.get_source() == u'console.log("hello, World!")'
        assert smap_view.get_source_name(0) == u'/test.js'

    def test_broken_base64(self):
        with pytest.raises(UnparseableSourcemap):
            fetch_sourcemap('data:application/json;base64,xxx')

    @responses.activate
    def test_garbage_json(self):
        responses.add(
            responses.GET, 'http://example.com', body='xxxx', content_type='application/json'
        )

        with pytest.raises(UnparseableSourcemap):
            fetch_sourcemap('http://example.com')

class TrimLineTest(TestCase):
    long_line = 'The public is more familiar with bad design than good design. It is, in effect, conditioned to prefer bad design, because that is what it lives with. The new becomes threatening, the old reassuring.'

    def test_simple(self):
        assert trim_line('foo') == 'foo'
        assert trim_line(
            self.long_line
        ) == 'The public is more familiar with bad design than good design. It is, in effect, conditioned to prefer bad design, because that is what it li {snip}'
        assert trim_line(
            self.long_line, column=10
        ) == 'The public is more familiar with bad design than good design. It is, in effect, conditioned to prefer bad design, because that is what it li {snip}'
        assert trim_line(
            self.long_line, column=66
        ) == '{snip} blic is more familiar with bad design than good design. It is, in effect, conditioned to prefer bad design, because that is what it lives wi {snip}'
        assert trim_line(
            self.long_line, column=190
        ) == '{snip} gn. It is, in effect, conditioned to prefer bad design, because that is what it lives with. The new becomes threatening, the old reassuring.'
        assert trim_line(
            self.long_line, column=9999
        ) == '{snip} gn. It is, in effect, conditioned to prefer bad design, because that is what it lives with. The new becomes threatening, the old reassuring.'

def test_get_culprit_is_patched():
    from sentry.lang.javascript.plugin import fix_culprit, generate_modules

    data = {
        'message': 'hello',
        'platform': 'javascript',
        'sentry.interfaces.Exception': {
            'values': [
                {
                    'type': 'Error',
                    'stacktrace': {
                        'frames': [
                            {
                                'abs_path': 'http://example.com/foo.js',
                                'filename': 'foo.js',
                                'lineno': 4,
                                'colno': 0,
                                'function': 'thing',
                            },
                            {
                                'abs_path': 'http://example.com/bar.js',
                                'filename': 'bar.js',
                                'lineno': 1,
                                'colno': 0,
                                'function': 'oops',
                            },
                        ],
                    },
                }
            ],
        }
    }
    generate_modules(data)
    fix_culprit(data)
    assert data['culprit'] == 'bar in oops'

def test_ensure_module_names():
    from sentry.lang.javascript.plugin import generate_modules
    data = {
        'message': 'hello',
        'platform': 'javascript',
        'sentry.interfaces.Exception': {
            'values': [
                {
                    'type': 'Error',
                    'stacktrace': {
                        'frames': [
                            {
                                'filename': 'foo.js',
                                'lineno': 4,
                                'colno': 0,
                                'function': 'thing',
                            },
                            {
                                'abs_path': 'http://example.com/foo/bar.js',
                                'filename': 'bar.js',
                                'lineno': 1,
                                'colno': 0,
                                'function': 'oops',
                            },
                        ],
                    },
                }
            ],
        }
    }
    generate_modules(data)
    exc = data['sentry.interfaces.Exception']['values'][0]
    assert exc['stacktrace']['frames'][1]['module'] == 'foo/bar'

class ErrorMappingTest(TestCase):
    @responses.activate
    def test_react_error_mapping_resolving(self):
        responses.add(
            responses.GET,
            REACT_MAPPING_URL,
            body=r'''
        {
          "108": "%s.getChildContext(): key \"%s\" is not defined in childContextTypes.",
          "109": "%s.render(): A valid React element (or null) must be returned. You may have returned undefined, an array or some other invalid object.",
          "110": "Stateless function components cannot have refs."
        }
        ''',
            content_type='application/json'
        )

        for x in range(3):
            data = {
                'platform': 'javascript',
                'sentry.interfaces.Exception': {
                    'values': [
                        {
                            'type':
                            'InvariantViolation',
                            'value': (
                                'Minified React error #109; visit http://facebook'
                                '.github.io/react/docs/error-decoder.html?invariant='
                                '109&args[]=Component for the full message or use '
                                'the non-minified dev environment for full errors '
                                'and additional helpful warnings.'
                            ),
                            'stacktrace': {
                                'frames': [
                                    {
                                        'abs_path': 'http://example.com/foo.js',
                                        'filename': 'foo.js',
                                        'lineno': 4,
                                        'colno': 0,
                                    },
                                    {
                                        'abs_path': 'http://example.com/foo.js',
                                        'filename': 'foo.js',
                                        'lineno': 1,
                                        'colno': 0,
                                    },
                                ],
                            },
                        }
                    ],
                }
            }

            assert rewrite_exception(data)

            assert data['sentry.interfaces.Exception']['values'][0]['value'] == (
                'Component.render(): A valid React element (or null) must be '
                'returned. You may have returned undefined, an array or '
                'some other invalid object.'
            )

    @responses.activate
    def test_react_error_mapping_empty_args(self):
        responses.add(
            responses.GET,
            REACT_MAPPING_URL,
            body=r'''
        {
          "108": "%s.getChildContext(): key \"%s\" is not defined in childContextTypes."
        }
        ''',
            content_type='application/json'
        )

        data = {
            'platform': 'javascript',
            'sentry.interfaces.Exception': {
                'values': [
                    {
                        'type':
                        'InvariantViolation',
                        'value': (
                            'Minified React error #108; visit http://facebook'
                            '.github.io/react/docs/error-decoder.html?invariant='
                            '108&args[]=Component&args[]= for the full message '
                            'or use the non-minified dev environment for full '
                            'errors and additional helpful warnings.'
                        ),
                        'stacktrace': {
                            'frames': [
                                {
                                    'abs_path': 'http://example.com/foo.js',
                                    'filename': 'foo.js',
                                    'lineno': 4,
                                    'colno': 0,
                                },
                            ],
                        },
                    }
                ],
            }
        }

        assert rewrite_exception(data)

        assert data['sentry.interfaces.Exception']['values'][0]['value'] == (
            'Component.getChildContext(): key "" is not defined in '
            'childContextTypes.'
        )

    @responses.activate
    def test_react_error_mapping_truncated(self):
        responses.add(
            responses.GET,
            REACT_MAPPING_URL,
            body=r'''
        {
          "108": "%s.getChildContext(): key \"%s\" is not defined in childContextTypes."
        }
        ''',
            content_type='application/json'
        )

        data = {
            'platform': 'javascript',
            'sentry.interfaces.Exception': {
                'values': [
                    {
                        'type':
                        'InvariantViolation',
                        'value': (
                            u'Minified React error #108; visit http://facebook'
                            u'.github.io/react/docs/error-decoder.html?\u2026'
                        ),
                        'stacktrace': {
                            'frames': [
                                {
                                    'abs_path': 'http://example.com/foo.js',
                                    'filename': 'foo.js',
                                    'lineno': 4,
                                    'colno': 0,
                                },
                            ],
                        },
                    }
                ],
            }
        }

        assert rewrite_exception(data)

        assert data['sentry.interfaces.Exception']['values'][0]['value'] == (
            '<redacted>.getChildContext(): key "<redacted>" is not defined in '
            'childContextTypes.'
        )


text:
layout: page
title: About Me
image:
  feature: abstract-5.jpg
comments: false
---

## My profile

我是仇鑫,大一网络工程专业。

熟悉C,了解C++,Python,HTML+CSS,	Linux/Unix,docker, Raspberry Pi.

vim初学者/轻度用户,oh-my-zsh初学者。

想做iOS开发。

##English Edition

Hi,I am Xin Qiu,you can call me CoderX.I am a freshman majoring in Network Engineering.

I know C,C++,Python,HTML+CSS,	Linux/Unix,docker,Raspberry Pi.

I want to be a iOS developer.

## Contact Me

[Email Me](mailto:xinqiu.94@gmail.com)

Fork Me