text:
<canvas id="canvas" width="100%" height="100%"/>

<style>
#tiling {
    border: 1px solid black;
}
html, body {
    margin: 0;
    padding: 0;
}
</style>

<script src="js/vector.js"></script>
<script src="js/resizer.js"></script>
<script src="js/mouser.js"></script>
<script src="js/primitives.js"></script>
<script>
var canvas = document.getElementById("canvas"),
    context = canvas.getContext("2d");

Resizer.installHandler(canvas);
Mouser.installHandler(canvas);

var swap = function (obj1, obj2, prop) {
    var temp = obj1[prop];
    obj1[prop] = obj2[prop];
    obj2[prop] = temp;
};

function randomColor() {
    return '#' + Math.floor(Math.random() * 0xFFFFFF).toString(16);
}

var epsilonEquals = function (x, y, epsilon) {
    if (!epsilon) {
        epsilon = 1e-4;
    }
    return Math.abs(x, y) < epsilon;
};

var Collidables = (function () {

var IntersectionType = {
    empty: 0,
    singlePoint: 1,
    range: 2
};

var Intersection = (function () {
    function Intersection(type, arg1, arg2, arg3, arg4) {
        this.type = type;
        switch (type) {
            case IntersectionType.empty:
                // Intentionally empty
            break;
            case IntersectionType.singlePoint:
                this.point = arg1;
            break;
            case IntersectionType.range:
                this.rangeStart = arg1;
                this.rangeEnd = arg2;
                this.parameterRangeStart = arg3;
                this.parameterRangeEnd = arg4;
            break;
            default:
                throw new Error("Invalid intersection type!");
        }
    }

    Intersection.prototype.getDrawable = function () {
        switch (this.type) {
            case IntersectionType.singlePoint:
                // Arbitrary radius
                return new Collidables.Circle(this.point, 10);
            break;
            case IntersectionType.range:
                return new Collidables.LineSegment(this.rangeStart, this.rangeEnd);
            break;
            default:
                return null;
        }
    };

    return Intersection;
})();

var Line = (function () {
    function Line(a, b) {
        // y = kx + b
        // k = dy / dx
        // b = y_i - kx_i
        this.slope = (a.y - b.y) / (a.x - b.x);
        this.offset = a.y - this.slope * a.x;
        // The line's standart equation is kx - y + b= 0,
        // Thus, normalize((k, -1)) is normal to the line while
        // normalize((1, k)) is collinear
        this.collinear = new Vector2(1, this.slope);
        this.collinear.normalize();
		this.point = a;
        this.color = randomColor();
    }

    Line.prototype.draw = function (context) {
        var firstVisiblePoint = new Vector2(0, this.offset);
        var canvasWidth = context.canvas.width;
        var lastVisiblePoint = new Vector2(canvasWidth,
                                           this.slope * canvasWidth + this.offset);
        context.save();
        context.strokeStyle = this.color;
        context.beginPath();
        context.moveTo(firstVisiblePoint.x, firstVisiblePoint.y);
        context.lineTo(lastVisiblePoint.x, lastVisiblePoint.y);
        context.stroke();
        context.restore();
    };

    Line.prototype.intersect = function (figure) {
        switch (figure.constructor) {
            case Collidables.Line:
            break;
            case Collidables.Rect:

            break;
            break;
        };
    };

    return Line;
})();

var LineSegment = (function () {
    function LineSegment(a, b) {
        this.startPoint = a;
        this.endPoint = b;
        this.line = new Collidables.Line(a, b);
        var self = this;
        Object.defineProperty(this, "color", {
            get: function () { return self.line.color; },
            set: function (value) { self.line.color = value; }
        });
    }

    LineSegment.prototype.draw = function (context) {
        context.save();
        context.strokeStyle = this.color;
        context.beginPath();
        context.moveTo(this.startPoint.x, this.startPoint.y);
        context.lineTo(this.endPoint.x, this.endPoint.y);
        context.stroke();
        context.restore();
    };

    LineSegment.prototype.intersect = function (figure) {
    };

    return LineSegment;
})();

var Rect = (function () {
    function Rect(topLeft, size) {
        this.topLeft =  topLeft;
        if (typeof size === "number") {
            size = new Vector2(size, size);
        }
        this.size = size;
        this.color = randomColor();
    };

    Rect.prototype.draw = function (context) {
        context.save();
        context.strokeStyle = this.color;
        context.strokeRect(this.topLeft.x, this.topLeft.y, this.size.x, this.size.y);
        context.restore();
    };

    return Rect;
})();

var Circle = (function () {
    function Circle(center, radius) {
        this.center = center;
        this.radius = radius;
        this.color = randomColor();
    }

    Circle.prototype.draw = function (context) {
        context.save();
        context.strokeStyle = this.color;
        context.beginPath();
        context.arc(this.center.x, this.center.y, this.radius, 0, 2 * Math.PI);
        context.closePath();
        context.stroke();
        context.restore();
    };

    return Circle;
})();

var Intersectors = {};

Intersectors.LineToLine = function (line1, line2) {
	// k1x + b1 = k2x + b2
	// k1x - k2x = b2 - b1
	// x = (b2 - b1) / (k1 - k2)
	if (epsilonEquals(line1.slope, line2.slope)) {
		return new Collidables.Intersection(IntersectionType.empty);
	}
	var x = (line2.offset - line1.offset) / (line1.slope - line2.slope);
	var y = line1.slope * x + line1.offset;
	return new Collidables.Intersection(IntersectionType.singlePoint, new Vector2(x, y));
};

Intersectors.LineToLine = function (line1, line2) {
	if (epsilonEquals(line1.collinear.x, 0) || epsilonEquals(line2.collinear.y, 0)) {
		return new Intersection(IntersectionType.none);
	}
	var mu1 = (line2.point.x + mu2 * col2x - P1x) / col1x
	// k1x + b1 = k2x + b2
	// k1x - k2x = b2 - b1
	// x = (b2 - b1) / (k1 - k2)
	if (epsilonEquals(line1.slope, line2.slope)) {
		return new Collidables.Intersection(IntersectionType.empty);
	}
	var x = (line2.offset - line1.offset) / (line1.slope - line2.slope);
	var y = line1.slope * x + line1.offset;
	return new Collidables.Intersection(IntersectionType.singlePoint, new Vector2(x, y));
};

Intersectors.LineToLineSegment = function (line, lineSegment) {
	var intersectionWithParentLine = intersect(line, lineSegment.line);
	console.log("##", intersectionWithParentLine);
	if (intersectionWithParentLine.type === IntersectionType.empty) {
		return intersectionWithParentLine;
	}
	var point = intersectionWithParentLine.point;
	var scalingVector = lineSegment.endPoint.sub(lineSegment.startPoint)
											.reciproc();
	var normalizedPoint = point.sub(lineSegment.startPoint)
							   .componentProduct(scalingVector);
	if (Vector2.zero.lte(normalizedPoint) &&
		normalizedPoint.lte(Vector2.unit)) {
		return intersectionWithParentLine;
	}
	return new Intersection(IntersectionType.empty);
};

Intersectors.LineToRect = function (line, rect) {
	// Let the area under the rect be defined as all points P such as
	//    rect.topLeft <= P <= rect.topLeft + rect.size
	// Let M = randomPointFromL + lambda * l.collinear.
	// See if there's an M for which the rect inequalities hold
	var pointFromLine = new Vector2(0, line.offset);
	var oneOverCollinear = new Vector2(1 / line.collinear.x,
									   1 / line.collinear.y);
	// topLeft <= pointFromLine + lambda * collinear
	var lowerBound = rect.topLeft.sub(pointFromLine)
								 .componentProduct(oneOverCollinear);
	// pointFromLine + lambda * collinear <= rect.topLeft + rect.size
	var upperBound = rect.topLeft.add(rect.size)
								 .sub(pointFromLine)
								 .componentProduct(oneOverCollinear);
	// If it was the case that either of collinear components was
	// negative, the inequalities containg it should be swapped
	if (line.collinear.x < 0) {
		swap(lowerBound, upperBound, "x");
	}
	if (line.collinear.y < 0) {
		swap(lowerBound, upperBound, "y");
	}

	// lambda must be bigger than both components of lowerBound
	// and smaller than both components of upperBound, so:
	lowerBound.x = lowerBound.y = lowerBound.maxComponent();
	upperBound.x = upperBound.y = upperBound.minComponent();
	if (!lowerBound.lte(upperBound)) {
		return new Intersection(IntersectionType.empty);
	}

	var pointLowerBound = lowerBound.componentProduct(line.collinear)
									.add(pointFromLine);
	var pointUpperBound = upperBound.componentProduct(line.collinear)
									.add(pointFromLine);
	return new Intersection(IntersectionType.range,
							pointLowerBound,
							pointUpperBound,
							lowerBound,
							upperBound);
};

var intersect = function (shape1, shape2) {
	var type1 = shape1.constructor;
	var type2 = shape2.constructor;
	var intersectionFunctionName = type1.name + "To" + type2.name;
	var intersectionFunction = Intersectors[intersectionFunctionName];
	if (!intersectionFunction) {
		var reverseFunction = Intersectors[intersectionFunctionName];
		var intersectionFunction = function (shape2, shape1) {
			return reverseFunction(shape1, shape2);
		};
	}
	return intersectionFunction(shape1, shape2);
};

return {
    IntersectionType: IntersectionType,
    Intersection: Intersection,
    Line: Line,
    LineSegment: LineSegment,
    Rect: Rect,
    Circle: Circle,
	intersect: intersect
};
})();

var figures = [
    new Collidables.Line(new Vector2(100, 100), new Vector2(200, 200)),
    new Collidables.Line(new Vector2(200, 200), new Vector2(400, 100)),
    new Collidables.Rect(new Vector2(120, 130), new Vector2(50, 300)),
    new Collidables.LineSegment(new Vector2(100, 350), new Vector2(350, 300)),
];
var intersect = Collidables.intersect;
figures.push(intersect(figures[0], figures[1]).getDrawable());
figures.push(intersect(figures[0], figures[2]).getDrawable());
figures.push(intersect(figures[0], figures[3]).getDrawable());
//figures[figures.length - 1].color = "black";

var update = function () {

    setTimeout(update, 1000);
}

var requestAnimationFrame = requestAnimationFrame || function (cb) {
	cb();
	setTimeout(cb, 1000 / 60);
};

var draw = function () {
    context.clearRect(0, 0, canvas.width, canvas.height);
    context.lineWidth = 5;

    figures.forEach(function (f) {
        f && f.draw(context);
    });
    requestAnimationFrame(draw);
}

draw();
</script>


text:
using System.Threading.Tasks;
using SF.Sys.Entities;
using SF.Sys.Auth;
using System;
using SF.Sys.Data;
using System.Linq;
using SF.Sys.Clients;
using SF.Sys;
using SF.Sys.TimeServices;
using System.Collections.Generic;
using SF.Sys.Linq;

namespace SF.Common.Conversations.Front
{

	/// <summary>
	/// 会话服务
	/// </summary>
	public class ConversationService : IConversationService
	{
		IDataScope DataScope { get; }
		IAccessToken AccessToken { get; }
		Lazy<Managers.ISessionStatusManager> SessionStatusManager { get; }
		Lazy<Managers.ISessionMemberStatusManager> SessionMemberStatusManager { get; }
		Lazy<Managers.ISessionMessageManager> SessionMessageManager { get; }
		Lazy<ITimeService> TimeService { get; }
		Lazy<IUserProfileService> UserProfileService { get; }
		IEnumerable<Providers.ISessionProvider> SessionProviders { get; }
		SF.Sys.Services.NamedServiceResolver<Providers.ISessionProvider> SessionProviderResolver { get; }

		public long EnsureUserIdent() =>
			AccessToken.User.EnsureUserIdent();

		public ConversationService(
			IDataScope DataScope,
			IAccessToken AccessToken,

			Lazy<Managers.ISessionStatusManager> SessionStatusManager,
			Lazy<Managers.ISessionMessageManager> SessionMessageManager,
			Lazy<Managers.ISessionMemberStatusManager> SessionMemberStatusManager,

			Lazy<ITimeService> TimeService,
			Lazy<IUserProfileService> UserProfileService,
			IEnumerable<Providers.ISessionProvider> SessionProviders,
			SF.Sys.Services.NamedServiceResolver<Providers.ISessionProvider> SessionProviderResolver
			)
		{
			this.AccessToken = AccessToken;
			this.DataScope = DataScope;
			this.SessionStatusManager= SessionStatusManager;
			this.SessionMemberStatusManager = SessionMemberStatusManager;
			this.SessionMessageManager = SessionMessageManager;
			this.TimeService = TimeService;
			this.UserProfileService = UserProfileService;
			this.SessionProviders = SessionProviders;
			this.SessionProviderResolver = SessionProviderResolver;
		}

		async Task<(Providers.ISessionProvider Provider,long UserId,DateTime JoinTime)> EnsureSessionMember(
			string BizIdentType,
			long BizIdent
			)
		{
			if (BizIdentType.IsNullOrEmpty())
				throw new PublicArgumentException("必须指定业务标识类型");
			if (BizIdent == 0)
				throw new PublicArgumentException("必须指定业务标识");

			var user = EnsureUserIdent();
			var provider = SessionProviderResolver(BizIdentType);
			if(provider==null)
				throw new PublicDeniedException("找不到会话类型:"+BizIdentType);
			var joinTime=await provider.MemberRelationValidate(BizIdent, user);
			return (provider, user, joinTime);
		}

		/// <summary>
		/// 查询会话消息
		/// </summary>
		/// <param name="Arg">查询参数</param>
		/// <returns></returns>
		public async Task<QueryResult<SessionMessage>> QueryMessages(MessageQueryArgument Arg)
		{
			var ctx =await EnsureSessionMember(Arg.BizIdentType,Arg.BizIdent);
			return await DataScope.Use("查询消息", async DataContext =>
			 {
				 var user = ctx.UserId;
				 var rq = from s in DataContext.Set<DataModels.DataSessionStatus>().AsQueryable()
						 where s.BizIdentType == Arg.BizIdentType &&
								 s.BizIdent == Arg.BizIdent &&
								 s.LogicState == EntityLogicState.Enabled
                          from m in s.Messages
                          where m.Time >= ctx.JoinTime

                         select new SessionMessage
						 {
							 Id = m.Id,
							 Argument = m.Argument,
							 SessionId = m.SessionId,
							 Text = m.Text,
							 Time = m.Time,
							 Type = m.Type,
							 UserId = m.UserId,
							 Self = m.UserId.HasValue && m.UserId.Value == user
						 };

				 if (Arg.StartId.HasValue)
					 rq = rq.Where(m => m.Id > Arg.StartId.Value).OrderBy(m => m.Id);
				 else if (Arg.EndId.HasValue)
					 rq = rq.Where(m => m.Id < Arg.EndId.Value).OrderByDescending(m => m.Id);
				 else
					 rq = rq.OrderByDescending(m => m.Id);

				 var re = await rq.ToQueryResultAsync(Arg.Paging);

				 var uids = re.Items.Select(i => i.UserId).Where(i => i.HasValue).Select(i => i.Value).ToArray();
				 var users = await ctx.Provider.GetMemberDesc(Arg.BizIdent, uids);

				 foreach (var i in re.Items)
					 if (i.UserId.HasValue && users.TryGetValue(i.UserId.Value, out var u))
					 {
						 i.PosterName = u.Name;
						 i.PosterIcon = u.Icon;
						 i.MemberBizIdent = u.BizIdent;
						 i.MemberBizIdentType = u.BizIdentType;
					 }

				 if (!Arg.StartId.HasValue)
					 re.Items = re.Items.OrderBy(i => i.Id).ToArray();

				 return re;
			 });
		}

		/// <summary>
		/// 发送会话消息
		/// </summary>
		/// <param name="Arg">消息发送参数</param>
		/// <returns>消息ID</returns>
		public async Task<ObjectKey<long>> SendMessage(MessageSendArgument Arg)
		{
			var ctx = await EnsureSessionMember(Arg.BizIdentType, Arg.BizIdent);
			var sid = await SessionStatusManager.Value.GetOrCreateSession(Arg.BizIdentType, Arg.BizIdent);

			var id =await SessionMessageManager.Value.CreateAsync(
				new Models.SessionMessage
				{
					SessionId= sid,
					Argument = Arg.Argument,
					Text = Arg.Text,
					UserId=ctx.UserId,
					Type = Arg.Type,
				});
			return id;
		}

		public async Task SetReadTime(SetReadTimeArgument Arg)
		{
			var ctx=await EnsureSessionMember(Arg.BizIdentType, Arg.BizIdent);
			var sid = await SessionStatusManager.Value.GetOrCreateSession(Arg.BizIdentType, Arg.BizIdent);

			await SessionMemberStatusManager.Value.SetReadTime(
				sid,
				ctx.UserId
				);
		}

		public async Task<QueryResult<SessionGroup>> QuerySessions(SessionQueryArgument Arg)
		{
			var user = EnsureUserIdent();
			var grps = new List<SessionGroup>();
			foreach (var sp in SessionProviders)
			{
				grps.AddRange(await sp.QuerySessions(user));
			}
			return await DataScope.Use("查询消息", async DataContext =>
			{

				var ssQuery = DataContext.Set<DataModels.DataSessionStatus>().AsQueryable();
				var Members = DataContext.Set<DataModels.DataSessionMemberStatus>().AsQueryable();

				//填充会话状态
				foreach (var g in from grp in grps
								  from s in grp.Sessions
								  group s by s.BizIdentType into g
								  select (
									  BizIdentType: g.Key,
									  BizIdents: g.Select(gi => gi.BizIdent).Distinct().ToArray(),
									  Sessions: g.ToArray()
									  )
								)
				{
					var dics = await (
						from s in ssQuery
						where s.BizIdentType == g.BizIdentType && g.BizIdents.Contains(s.BizIdent)
						join tm in Members on s.Id equals tm.SessionId into tms
						from m in tms.Where(tm => tm.OwnerId.Value == user).DefaultIfEmpty()
							//let m= s.Members.Where(m => m.OwnerId.Value == user).SingleOrDefault()
						let readed = m == null ? 0 : m.MessageReaded
						select new
						{
							s.BizIdent,
							s.BizIdentType,
							s.LogicState,
							Unread = s.MessageCount - readed,
							s.UpdatedTime,
							s.LastMessageText
						}).ToDictionaryAsync(s => (s.BizIdentType, s.BizIdent));

					foreach (var s in g.Sessions)
						if (dics.TryGetValue((s.BizIdentType, s.BizIdent), out var ss))
						{
							s.Unread = ss.Unread;

                            //只有加入时间比消息时间早,才显示消息
                            if (s.JoinTime <= ss.UpdatedTime)
                            {
                                s.Text = s.Text ?? ss.LastMessageText;
                                s.Time = s.Time ?? ss.UpdatedTime;
                            }
						}
				}

				var q = from g in grps
						from s in g.Sessions
						group (g, s) by g.Name into gi
						let fg = gi.First().g
						orderby fg.Order
						select new SessionGroup
						{
							Name = fg.Name,
							Text = fg.Text,
							Sessions = gi.Select(p => p.s)
									  .OrderByDescending(s => s.Time)
									  .ToArray()
						};
				var items = q.ToArray();
				return new QueryResult<SessionGroup>
				{
					Items = items
				};
			});
		}
		public async Task<QueryResult<SessionMember>> QueryMembers(MemberQueryArgument Arg)
		{
			var ctx = await EnsureSessionMember(Arg.BizIdentType, Arg.BizIdent);
			var items = await ctx.Provider.QueryMembers(Arg.BizIdent);

			return new QueryResult<SessionMember>
			{
				Items = items
			};

		}
	}
}

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML>

        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />

        <link rel="stylesheet" href="../vanilla.modal.css" type="text/css" media="screen" />

Vanilla modal

Open and close modal with link

Add data-modal attribute to your links and use href attribute to define what should be opened in the modal.

        Click to open

            Lorem ipsum

    <a href="#example-1" data-modal>Click to open</a>
    <div id="example-1" class="example">
        Lorem ipsum
    </div>

Open and close modal with AJAX

This example opens the modal automatically and load the page content into modal with AJAX.

        Click to open

    <a href="ajax.html" data-modal>Click to open</a>

            The following example shows how you can manually load AJAX page into a modal.

            Note : Ajax response must be wrapped in a div with class vanilla-modal-content

        Click to open

    <a href="ajax.html" id="example-ajax">Click to open</a>
    <script type="text/javascript">
    vanilla('#example-ajax').on('click', function(event){
        event.preventDefault();
        vanilla(this).modal();
    });
    </script>

Options

    vanilla.modal.defaults = {
        opacity: 0.75,              // Overlay opacity
        overlay: '#000',            // Overlay color
        showSpinner: true,          // Show spinner on loading
        zIndex: 1,                  // Overlay z-index
    }


text:
from __future__ import unicode_literals

__author__ = "raz"

try:
    import dxfwrite
except ImportError:
    # if dxfwrite is not 'installed' append parent dir of __file__ to sys.path
    import os, sys
    curdir = os.path.dirname(os.path.abspath(__file__))
    sys.path.insert(0, os.path.abspath(os.path.join(curdir, os.path.pardir)))

from dxfwrite import DXFEngine as dxf

drawing = dxf.drawing('unicode_text.dxf')
drawing.add(dxf.line((0, 0), (24, 0), color=7))
layer_name = 'ŽĆČĐŠ'
drawing.add_layer(layer_name, color=2)
drawing.add(dxf.text(
    'На крај села жута ћирилична кућа', insert=(0, 0.2), layer=layer_name
))
drawing.save()


text:
package edu.cwu.rrdtp;

import com.sun.jna.Pointer;
import com.sun.jna.NativeLong;

/**
 * Entry used to store the actual data values. Currently a work-in-progress.
 */
public class LongEntry extends Entry
{
    public LongEntry(Pointer self)
	{
		super(self);
	}

	public final void Set(long val)
	{
		NativeLibrary.rrdtp_LongEntry_Set(self, new NativeLong(val));
	}

	public final long Get()
	{
		return NativeLibrary.rrdtp_LongEntry_Get(self).longValue();
	}

	@Override
	public String toString()
	{
		return Long.toString(Get());
	}
}


text:
<?php declare(strict_types=1);

namespace SebastianBergmann\Type;

use Throwable;

interface Exception extends Throwable
{
}


text:
package asm

import (
	"bufio"
	"bytes"
	"fmt"
	"io/ioutil"
	"os"
	"path/filepath"
	"regexp"
	"sort"
	"strconv"
	"strings"
	"testing"

	"cmd/asm/internal/lex"
	"cmd/internal/obj"
	"cmd/internal/objabi"
)

// An end-to-end test for the assembler: Do we print what we parse?
// Output is generated by, in effect, turning on -S and comparing the
// result against a golden file.

func testEndToEnd(t *testing.T, goarch, file string) {
	input := filepath.Join("testdata", file+".s")
	architecture, ctxt := setArch(goarch)
	architecture.Init(ctxt)
	lexer := lex.NewLexer(input)
	parser := NewParser(ctxt, architecture, lexer)
	pList := new(obj.Plist)
	var ok bool
	testOut = new(bytes.Buffer) // The assembler writes test output to this buffer.
	ctxt.Bso = bufio.NewWriter(os.Stdout)
	defer ctxt.Bso.Flush()
	failed := false
	ctxt.DiagFunc = func(format string, args ...interface{}) {
		failed = true
		t.Errorf(format, args...)
	}
	pList.Firstpc, ok = parser.Parse()
	if !ok || failed {
		t.Errorf("asm: %s assembly failed", goarch)
		return
	}
	output := strings.Split(testOut.String(), "\n")

	// Reconstruct expected output by independently "parsing" the input.
	data, err := ioutil.ReadFile(input)
	if err != nil {
		t.Error(err)
		return
	}
	lineno := 0
	seq := 0
	hexByLine := map[string]string{}
	lines := strings.SplitAfter(string(data), "\n")
Diff:
	for _, line := range lines {
		lineno++

		// Ignore include of textflag.h.
		if strings.HasPrefix(line, "#include ") {
			continue
		}

		// The general form of a test input line is:
		//	// comment
		//	INST args [// printed form] [// hex encoding]
		parts := strings.Split(line, "//")
		printed := strings.TrimSpace(parts[0])
		if printed == "" || strings.HasSuffix(printed, ":") { // empty or label
			continue
		}
		seq++

		var hexes string
		switch len(parts) {
		default:
			t.Errorf("%s:%d: unable to understand comments: %s", input, lineno, line)
		case 1:
			// no comment
		case 2:
			// might be printed form or hex
			note := strings.TrimSpace(parts[1])
			if isHexes(note) {
				hexes = note
			} else {
				printed = note
			}
		case 3:
			// printed form, then hex
			printed = strings.TrimSpace(parts[1])
			hexes = strings.TrimSpace(parts[2])
			if !isHexes(hexes) {
				t.Errorf("%s:%d: malformed hex instruction encoding: %s", input, lineno, line)
			}
		}

		if hexes != "" {
			hexByLine[fmt.Sprintf("%s:%d", input, lineno)] = hexes
		}

		// Canonicalize spacing in printed form.
		// First field is opcode, then tab, then arguments separated by spaces.
		// Canonicalize spaces after commas first.
		// Comma to separate argument gets a space; comma within does not.
		var buf []byte
		nest := 0
		for i := 0; i < len(printed); i++ {
			c := printed[i]
			switch c {
			case '{', '[':
				nest++
			case '}', ']':
				nest--
			case ',':
				buf = append(buf, ',')
				if nest == 0 {
					buf = append(buf, ' ')
				}
				for i+1 < len(printed) && (printed[i+1] == ' ' || printed[i+1] == '\t') {
					i++
				}
				continue
			}
			buf = append(buf, c)
		}

		f := strings.Fields(string(buf))

		// Turn relative (PC) into absolute (PC) automatically,
		// so that most branch instructions don't need comments
		// giving the absolute form.
		if len(f) > 0 && strings.HasSuffix(printed, "(PC)") {
			last := f[len(f)-1]
			n, err := strconv.Atoi(last[:len(last)-len("(PC)")])
			if err == nil {
				f[len(f)-1] = fmt.Sprintf("%d(PC)", seq+n)
			}
		}

		if len(f) == 1 {
			printed = f[0]
		} else {
			printed = f[0] + "\t" + strings.Join(f[1:], " ")
		}

		want := fmt.Sprintf("%05d (%s:%d)\t%s", seq, input, lineno, printed)
		for len(output) > 0 && (output[0] < want || output[0] != want && len(output[0]) >= 5 && output[0][:5] == want[:5]) {
			if len(output[0]) >= 5 && output[0][:5] == want[:5] {
				t.Errorf("mismatched output:\nhave %s\nwant %s", output[0], want)
				output = output[1:]
				continue Diff
			}
			t.Errorf("unexpected output: %q", output[0])
			output = output[1:]
		}
		if len(output) > 0 && output[0] == want {
			output = output[1:]
		} else {
			t.Errorf("missing output: %q", want)
		}
	}
	for len(output) > 0 {
		if output[0] == "" {
			// spurious blank caused by Split on "\n"
			output = output[1:]
			continue
		}
		t.Errorf("unexpected output: %q", output[0])
		output = output[1:]
	}

	// Checked printing.
	// Now check machine code layout.

	top := pList.Firstpc
	var text *obj.LSym
	ok = true
	ctxt.DiagFunc = func(format string, args ...interface{}) {
		t.Errorf(format, args...)
		ok = false
	}
	obj.Flushplist(ctxt, pList, nil, "")

	for p := top; p != nil; p = p.Link {
		if p.As == obj.ATEXT {
			text = p.From.Sym
		}
		hexes := hexByLine[p.Line()]
		if hexes == "" {
			continue
		}
		delete(hexByLine, p.Line())
		if text == nil {
			t.Errorf("%s: instruction outside TEXT", p)
		}
		size := int64(len(text.P)) - p.Pc
		if p.Link != nil {
			size = p.Link.Pc - p.Pc
		} else if p.Isize != 0 {
			size = int64(p.Isize)
		}
		var code []byte
		if p.Pc < int64(len(text.P)) {
			code = text.P[p.Pc:]
			if size < int64(len(code)) {
				code = code[:size]
			}
		}
		codeHex := fmt.Sprintf("%x", code)
		if codeHex == "" {
			codeHex = "empty"
		}
		ok := false
		for _, hex := range strings.Split(hexes, " or ") {
			if codeHex == hex {
				ok = true
				break
			}
		}
		if !ok {
			t.Errorf("%s: have encoding %s, want %s", p, codeHex, hexes)
		}
	}

	if len(hexByLine) > 0 {
		var missing []string
		for key := range hexByLine {
			missing = append(missing, key)
		}
		sort.Strings(missing)
		for _, line := range missing {
			t.Errorf("%s: did not find instruction encoding", line)
		}
	}

}

func isHexes(s string) bool {
	if s == "" {
		return false
	}
	if s == "empty" {
		return true
	}
	for _, f := range strings.Split(s, " or ") {
		if f == "" || len(f)%2 != 0 || strings.TrimLeft(f, "0123456789abcdef") != "" {
			return false
		}
	}
	return true
}

// It would be nice if the error messages began with
// the standard file:line: prefix,
// but that's not where we are today.
// It might be at the beginning but it might be in the middle of the printed instruction.
var fileLineRE = regexp.MustCompile(`(?:^|\()(testdata[/\\][0-9a-z]+\.s:[0-9]+)(?:$|\))`)

// Same as in test/run.go
var (
	errRE       = regexp.MustCompile(`// ERROR ?(.*)`)
	errQuotesRE = regexp.MustCompile(`"([^"]*)"`)
)

func testErrors(t *testing.T, goarch, file string) {
	input := filepath.Join("testdata", file+".s")
	architecture, ctxt := setArch(goarch)
	lexer := lex.NewLexer(input)
	parser := NewParser(ctxt, architecture, lexer)
	pList := new(obj.Plist)
	var ok bool
	testOut = new(bytes.Buffer) // The assembler writes test output to this buffer.
	ctxt.Bso = bufio.NewWriter(os.Stdout)
	defer ctxt.Bso.Flush()
	failed := false
	var errBuf bytes.Buffer
	ctxt.DiagFunc = func(format string, args ...interface{}) {
		failed = true
		s := fmt.Sprintf(format, args...)
		if !strings.HasSuffix(s, "\n") {
			s += "\n"
		}
		errBuf.WriteString(s)
	}
	pList.Firstpc, ok = parser.Parse()
	obj.Flushplist(ctxt, pList, nil, "")
	if ok && !failed {
		t.Errorf("asm: %s had no errors", goarch)
	}

	errors := map[string]string{}
	for _, line := range strings.Split(errBuf.String(), "\n") {
		if line == "" || strings.HasPrefix(line, "\t") {
			continue
		}
		m := fileLineRE.FindStringSubmatch(line)
		if m == nil {
			t.Errorf("unexpected error: %v", line)
			continue
		}
		fileline := m[1]
		if errors[fileline] != "" && errors[fileline] != line {
			t.Errorf("multiple errors on %s:\n\t%s\n\t%s", fileline, errors[fileline], line)
			continue
		}
		errors[fileline] = line
	}

	// Reconstruct expected errors by independently "parsing" the input.
	data, err := ioutil.ReadFile(input)
	if err != nil {
		t.Error(err)
		return
	}
	lineno := 0
	lines := strings.Split(string(data), "\n")
	for _, line := range lines {
		lineno++

		fileline := fmt.Sprintf("%s:%d", input, lineno)
		if m := errRE.FindStringSubmatch(line); m != nil {
			all := m[1]
			mm := errQuotesRE.FindAllStringSubmatch(all, -1)
			if len(mm) != 1 {
				t.Errorf("%s: invalid errorcheck line:\n%s", fileline, line)
			} else if err := errors[fileline]; err == "" {
				t.Errorf("%s: missing error, want %s", fileline, all)
			} else if !strings.Contains(err, mm[0][1]) {
				t.Errorf("%s: wrong error for %s:\n%s", fileline, all, err)
			}
		} else {
			if errors[fileline] != "" {
				t.Errorf("unexpected error on %s: %v", fileline, errors[fileline])
			}
		}
		delete(errors, fileline)
	}
	var extra []string
	for key := range errors {
		extra = append(extra, key)
	}
	sort.Strings(extra)
	for _, fileline := range extra {
		t.Errorf("unexpected error on %s: %v", fileline, errors[fileline])
	}
}

func Test386EndToEnd(t *testing.T) {
	defer func(old string) { objabi.GO386 = old }(objabi.GO386)
	for _, go386 := range []string{"387", "sse2"} {
		t.Logf("GO386=%v", go386)
		objabi.GO386 = go386
		testEndToEnd(t, "386", "386")
	}
}

func TestARMEndToEnd(t *testing.T) {
	defer func(old int) { objabi.GOARM = old }(objabi.GOARM)
	for _, goarm := range []int{5, 6, 7} {
		t.Logf("GOARM=%d", goarm)
		objabi.GOARM = goarm
		testEndToEnd(t, "arm", "arm")
		if goarm == 6 {
			testEndToEnd(t, "arm", "armv6")
		}
	}
}

func TestARMErrors(t *testing.T) {
	testErrors(t, "arm", "armerror")
}

func TestARM64EndToEnd(t *testing.T) {
	testEndToEnd(t, "arm64", "arm64")
}

func TestARM64Encoder(t *testing.T) {
	testEndToEnd(t, "arm64", "arm64enc")
}

func TestARM64Errors(t *testing.T) {
	testErrors(t, "arm64", "arm64error")
}

func TestAMD64EndToEnd(t *testing.T) {
	testEndToEnd(t, "amd64", "amd64")
}

func TestAMD64Encoder(t *testing.T) {
	testEndToEnd(t, "amd64", "amd64enc")
	testEndToEnd(t, "amd64", "amd64enc_extra")
}

func TestAMD64Errors(t *testing.T) {
	testErrors(t, "amd64", "amd64error")
}

func TestMIPSEndToEnd(t *testing.T) {
	testEndToEnd(t, "mips", "mips")
	testEndToEnd(t, "mips64", "mips64")
}

func TestPPC64EndToEnd(t *testing.T) {
	testEndToEnd(t, "ppc64", "ppc64")
}

func TestPPC64Encoder(t *testing.T) {
	testEndToEnd(t, "ppc64", "ppc64enc")
}

func TestS390XEndToEnd(t *testing.T) {
	testEndToEnd(t, "s390x", "s390x")
}


text:
package org.kuali.rice.krad.uif.service;

import org.kuali.rice.krad.uif.UifConstants;
import org.kuali.rice.krad.uif.view.View;
import org.kuali.rice.krad.uif.UifConstants.ViewType;
import org.springframework.beans.PropertyValues;

import java.util.Map;

/**
 * Provides methods handing View instance of certain types
 *
 *

 * The type service is invoked to handle type parameters that can be used for
 * additional indexing of views and retrieval.
 *

 *
 *

 * As the view dictionary entries are indexed the associated view type will be
 * retrieved and if there is an associated ViewTypeService it will
 * be invoked to provide parameter information for further indexing. This is
 * useful to index a view based on other properties, like a class name.
 *

 *
 * @author Kuali Rice Team (rice.collab@kuali.org)
 */
public interface ViewTypeService {

	/**
	 * Gives the view type name that is supported by the type service
	 *
	 *

	 * The name is used to associated a type (and thus a view type service) with
	 * a view instance through the view type name property. Thus must be unique
	 * among all view types implemented
	 *

	 *
	 * @return ViewType view type name
	 */
	public ViewType getViewTypeName();

	/**
	 * Pulls values for the supported parameters from the views configured property values. These
     * name/value pairs are used to index the view for later retrieval
	 *
	 * @param propertyValues - property values configured on the view bean definition
	 * @return Map<String, String> of parameters where map key is the parameter
	 *         name, and the map value is the parameter value
	 */
	public Map<String, String> getParametersFromViewConfiguration(PropertyValues propertyValues);

	/**
	 * Pulls entries from the given map that are supported parameters for the view type. In addition,
     * defaults can be set or additional parameters set as needed. Used by the ViewService to retrieve a
	 * View instance based on the incoming request parameters
	 *
	 * @param requestParameters
	 *            - Map of request parameters to pull view type parameters from
	 * @return Map<String, String> of parameters where map key is the parameter
	 *         name, and the map value is the parameter value
	 */
	public Map<String, String> getParametersFromRequest(Map<String, String> requestParameters);

}


text:
package com.linkedin.thirdeye.detector.email.filter;

import com.linkedin.thirdeye.datalayer.dto.MergedAnomalyResultDTO;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Properties;

public class DummyAlertFilter extends BaseAlertFilter {
  @Override
  public List<String> getPropertyNames() {
    return Collections.EMPTY_LIST;
  }

  @Override
  public void setParameters(Map<String, String> props) {
    // Does nothing
  }

  @Override
  public boolean isQualified(MergedAnomalyResultDTO anomaly) {
    return true;
  }

  @Override
  public String toString() {
    return "DummyFilter";
  }
}


text:
PriceTracker = {
  name = "PriceTracker",
  title = "Price Tracker",
  author = "@uladz, Garkin, Barvazon",
  version = "2.7.0",
	dbVersion = 0.3,

	colors = {
		default = "|c" .. ZO_TOOLTIP_DEFAULT_COLOR:ToHex(),
		instructional = "|c" .. ZO_TOOLTIP_INSTRUCTIONAL_COLOR:ToHex(),
		title = "|c00B5FF",
	},

  isSearching = false,
	selectedItem = {},
}
local PriceTracker = PriceTracker

-- List of support suggested price calculation algorithms.
PriceTracker.algorithmTable = {
	"Average",
	"Median",
	"Most Frequently Used",
	"Weighted Average",
}

-- Addon initialization.
function PriceTracker:OnLoad(eventCode, addOnName)
  if(addOnName ~= self.name) then
    return
  end

  -- Register for relevant trading house events.
  EVENT_MANAGER:RegisterForEvent("OnSearchResultsReceived",
      EVENT_TRADING_HOUSE_SEARCH_RESULTS_RECEIVED,
      function(...) self:OnSearchResultsReceived(...) end)
  EVENT_MANAGER:RegisterForEvent("OnSearchResultsError",
      EVENT_TRADING_HOUSE_ERROR,
      function(...) self:OnSearchResultsError(...) end)
	EVENT_MANAGER:RegisterForEvent("OnTradingHouseOpened",
      EVENT_OPEN_TRADING_HOUSE,
      function(...) self:OnTradingHouseOpened(...) end)
  EVENT_MANAGER:RegisterForEvent("OnTradingHouseClosed",
      EVENT_CLOSE_TRADING_HOUSE,
      function(...) self:OnTradingHouseClosed(...) end)
	EVENT_MANAGER:RegisterForEvent("OnTradingHouseCooldown",
      EVENT_TRADING_HOUSE_SEARCH_COOLDOWN_UPDATE,
      function(...) self:OnTradingHouseCooldown(...) end)

  -- ???
	LINK_HANDLER:RegisterCallback(LINK_HANDLER.LINK_CLICKED_EVENT,
      self.OnLinkClicked, self)
	LINK_HANDLER:RegisterCallback(LINK_HANDLER.LINK_MOUSE_UP_EVENT,
      self.OnLinkClicked, self)

  -- Register for item tooltip events.
	ZO_PreHookHandler(ItemTooltip, "OnUpdate",
      function() self:OnUpdateTooltip(moc(), ItemTooltip) end)
	ZO_PreHookHandler(ItemTooltip, "OnHide",
      function() self:OnHideTooltip(ItemTooltip) end)
	ZO_PreHookHandler(PopupTooltip, "OnUpdate",
      function() self:OnUpdateTooltip(self.clickedItem, PopupTooltip) end)
	ZO_PreHookHandler(PopupTooltip, "OnHide",
      function() self:OnHideTooltip(PopupTooltip) end)

  -- Automatically disable [Scan Prices] button when user performs search.
	ZO_PreHook("ExecuteTradingHouseSearch",
      function() self.scanButton:SetEnabled(false) end)

  -- Forward OnLoad event to enchanting table handler.
	PriceTracker.enchantingTable:OnLoad(eventCode, addOnName)

  -- Register chat commands.
	SLASH_COMMANDS["/pt"] = function(...) self:CommandHandler(...) end
	SLASH_COMMANDS["/pricetracker"] = function(...) self:CommandHandler(...) end

  -- Load saved settings.
	local defaults = {
		itemList = {},
		algorithm = self.algorithmTable[4],
		showMinMax = true,
		showSeen = false,
		showWasntSeen = false,
		showMath = false,
		ignoreFilters = false,
		historyDays = 30,
		ignoreFewItems = false,
		keyPress = self.menu.keyTable[1],
		isPlaySound = true,
		playSound = self.menu.soundTable[1],
	}
	self.db = ZO_SavedVars:NewAccountWide(
      self.name.."Settings",
      self.dbVersion,
      nil,
      defaults)

	-- Do some housekeeping and remove inparsable/invalid items from database.
	self:Housekeeping()

	-- Create the addon setting menu.
	self.menu:InitAddonMenu()

	-- Create Price Tracker buttons in the trading house window. Note that second
	-- button [Stop Scan] is initially hidden.
	self.scanButton = PriceTrackerControlButton
	self.scanButton:SetParent(ZO_TradingHouseLeftPaneBrowseItemsCommon)
	self.scanButton:SetWidth(ZO_TradingHouseLeftPaneBrowseItemsCommonQuality:GetWidth())
	self.stopButton = PriceTrackerStopButton
	self.stopButton:SetParent(ZO_TradingHouseLeftPaneBrowseItemsCommon)
	self.stopButton:SetWidth(ZO_TradingHouseLeftPaneBrowseItemsCommonQuality:GetWidth())

	self.scanButton = PriceTrackerControlButton

	-- Publish addon API.
	local libAA = LibStub:GetLibrary("LibAddonAPI")
	libAA:RegisterAddon(self.name, 1)
end

-- Handle /slash commands.
function PriceTracker:CommandHandler(text)
	text = text:lower()

	-- User options.
	if #text == 0 or text == "help" then
		self:ShowHelp()
		return
	end
	if text == "setup" then
		self.menu:OpenSettings()
		return
	end
	if text == "reset" then
		self.db.itemList = {}
		return
	end
	if text:find("^clean") then
		local days = select(3, text:find("^clean (%d+)"))
		days = tonumber(days) or 30
		self:CleanItemList(days)
		return
	end
	if text == "stats" then
		self:ShowStats()
		return
	end

	-- Hidden options.
	if text == "housekeeping" then
		self:Housekeeping()
		return
	end
end

-- Print help info.
function PriceTracker:ShowHelp()
	d("To scan all item prices in all guild stores, click the [Scan Prices] button in the guild store window. You can also scan prices of other guild store while at a vendor. Press [Stop Scan] if you want to abort scan.")
	d(" ")
	d("Other commands: ")
	d("/pt help - Show this help.")
	d("/pt clean <days> - Remove prices older then <days> (30 days if not specified).")
	d("/pt reset - Remove all stored price values.")
	d("/pt setup - Open the addon settings menu.")
end

-- Prints out database statistics.
function PriceTracker:ShowStats()
	local itemsCnt = 0
	local uniqueCnt = 0
	local recordsCnt = 0
	local oldestTime = 2147483647
	local newestTime = 0
	for k, v in pairs(self.db.itemList) do
		itemsCnt = itemsCnt + 1
		for level, item in pairs(v) do
			uniqueCnt = uniqueCnt + 1
			for itemK, itemV in pairs(item) do
				recordsCnt = recordsCnt + 1
				oldestTime = zo_min(oldestTime, itemV.expiry)
				newestTime = zo_max(newestTime, itemV.expiry)
			end
		end
	end
	oldestTime = zo_round((GetTimeStamp() + 30*86400 - oldestTime)/86400)
	newestTime = zo_round((GetTimeStamp() + 30*86400 - newestTime)/86400)
	d("Price Tracker statistics:")
	d("- Number of known items = "..itemsCnt)
	d("- Number of unique items = "..uniqueCnt)
	d("- Number of price records = "..recordsCnt)
	d("- Oldest time stamp = "..oldestTime.." day(s) ago")
	d("- Newest time stamp = "..newestTime.." day(s) ago")
end

-- This method makes sure the item list is intact and parsable, in order to
-- avoid exceptions later on. It runs only once on loading the addon.
function PriceTracker:Housekeeping()
	-- First time ever addon loaded.
	if not self.db.itemList then
		self.db.itemList = {}
		return
	end

	-- Expiry is time listed + 30 days. So if I want to keep items for 60 days,
	-- we have to use historyDays - 30.
	local timestamp = GetTimeStamp() - 86400 * (self.db.historyDays - 30)
	for k, v in pairs(self.db.itemList) do
		if type(k) ~= "string" or #k > 5 then
			self.db.itemList[k] = nil
		else
			for level, item in pairs(v) do
				for itemK, itemV in pairs(item) do
					-- Remove invalid and expired items.
					if itemV.purchasePrice == nil
							or itemV.stackCount == nil
							or type(itemV.name) ~= "string"
							or type(itemV.expiry) ~= "number"
							or itemV.expiry < timestamp then
						item[itemK] = nil
					-- Remove redundant keys from older data.
					else
						itemV.normalizedName = nil
						itemV.icon = nil
						itemV.sellerName = nil
						itemV.eachPrice = nil
					end
				end
				if next(item) == nil then
					v[level] = nil
				end
			end
		end
		if next(v) == nil then
			self.db.itemList[k] = nil
		end
	end
end

local function Collect(tooltip, object)
	if not tooltip.pt_objects then
		tooltip.pt_objects = {}
	end
	table.insert(tooltip.pt_objects, object)
end

local function AddDivider(tooltip)
	if not tooltip.pt_dividerPool then
		tooltip.pt_dividerPool = ZO_ControlPool:New(
			"ZO_BaseTooltipDivider",
			tooltip,
			"PT_Divider")
	end
	local div = tooltip.pt_dividerPool:AcquireObject()
	tooltip:AddControl(div)
	div:SetAnchor(CENTER)
	div:SetHidden(false)
	Collect(tooltip, div)
	tooltip:AddVerticalPadding(-10)
end

local function AddLine(tooltip, text, font, align)
	if not tooltip.pt_labelPool then
		tooltip.pt_labelPool = ZO_ControlPool:New(
			"ZO_TooltipLabel",
			tooltip,
			"PT_Label")
	end
	if not font then
		font = "ZoFontGame"
	end
	if not align then
		align = TEXT_ALIGN_CENTER
	end
	local label = tooltip.pt_labelPool:AcquireObject()
	tooltip:AddControl(label)
	label:SetAnchor(CENTER)
	label:SetWidth(tooltip:GetWidth())
	label:SetHorizontalAlignment(align)
	label:SetFont(font)
	label:SetText(text)
	label:SetHidden(false)
	Collect(tooltip, label)
	if text == "" then
		label:SetHeight(0)
	elseif align ~= TEXT_ALIGN_LEFT then
		tooltip:AddVerticalPadding(-10)
	end
end

local function AddPadding(tooltip, height)
	if not tooltip.pt_labelPool then
		tooltip.pt_labelPool = ZO_ControlPool:New(
			"ZO_TooltipLabel",
			tooltip,
			"PT_Label")
	end
	local pad = tooltip.pt_labelPool:AcquireObject()
	tooltip:AddControl(pad)
	pad:SetAnchor(CENTER)
	pad:SetWidth(tooltip:GetWidth())
	pad:SetHeight(height+10)
	pad:SetText("")
	pad:SetHidden(false)
	Collect(tooltip, pad)
	tooltip:AddVerticalPadding(-10)
end

local function AddLine2(tooltip, leftText, rightText)
	AddLine(tooltip, leftText, "ZoFontGame", TEXT_ALIGN_LEFT)
	tooltip:AddVerticalPadding(-32)
	AddLine(tooltip, rightText, "ZoFontGame", TEXT_ALIGN_RIGHT)
end

local function ReleaseAllObjects(tooltip)
	if tooltip.pt_dividerPool then
		tooltip.pt_dividerPool:ReleaseAllObjects()
	end
	if tooltip.pt_labelPool then
		tooltip.pt_labelPool:ReleaseAllObjects()
	end
	tooltip.pt_objects = nil
	tooltip.pt_init = nil
end

local function HideAllObjects(tooltip)
	if not tooltip.pt_objects then
		return
	end
	for k, v in pairs(tooltip.pt_objects) do
		v:SetHidden(true)
	end
end

local function ShowAllObjects(tooltip)
	if not tooltip.pt_objects then
		return
	end
	for _, object in pairs(tooltip.pt_objects) do
		object:SetHidden(false)
	end
end

-- Called when a tooltip is created or when any condition has changed, like
-- key was pressed or mouse moved. Anything that can change what's displayed
-- in the tooltip.
function PriceTracker:OnUpdateTooltip(item, tooltip)
	if not tooltip then
    tooltip = ItemTooltip
	end
	if not item
			or not item.dataEntry
			or not item.dataEntry.data then
		-- Tooltip has moved to another item but there is no Price Tracker info to
		-- show. Treat as hiding tooltip to avoid bug that no PT info is shown when
		-- returning back to the last item.
		self:OnHideTooltip(tooltip)
		return
	end
	if self.selectedItem[tooltip] == item then
		-- Tooltip already showing this item's Price Tracker info, do not rebuilt
		-- labels otherwise PT information will be duplicated. Only trace key modifiers
		-- to show or hide existing PT info in the tooltip.
		if self.menu:IsKeyPressed() then
			ShowAllObjects(tooltip)
		else
			HideAllObjects(tooltip)
		end
		return
	else
		-- New item selected, which means that the tooltip was reset and we need
		-- to clean up PT labels also and rebuilt PT info labels from scratch.
		self:OnHideTooltip(tooltip)
		if not self.menu:IsKeyPressed() then
			-- If the key modifier is not pressed, treat no PT info available, PT info
			-- will be added later when the key is pressed and this update function
			-- is called again.
			return
		end
	end

	-- New item was selected, add Price Tracke info to this tooltip.
	self.selectedItem[tooltip] = item

	-- Get number of items or stacks.
	local stackCount = item.dataEntry.data.stackCount
			or item.dataEntry.data.stack
			or item.dataEntry.data.count
	if not stackCount then
		return
	end

	-- Get item metadata.
	local itemId, level, quality
	local itemLink = self:GetItemLink(item)
	if itemLink then
		_, _, _, itemId = ZO_LinkHandler_ParseLink(itemLink)
		level = self:GetItemLevel(itemLink)
		quality = GetItemLinkQuality(itemLink)
	else
		if item.dataEntry
				and item.dataEntry.data
				and item.dataEntry.data.itemId then
			itemId = item.dataEntry.data.itemId
			level = tonumber(item.dataEntry.data.level)
			quality = item.dataEntry.data.quality
		else
			return
		end
	end

	-- Search internal prices database.
	local matches = self:GetMatches(itemId, level, quality)

	-- Add title.
	if matches or self.db.showWasntSeen then
		AddPadding(tooltip, 5)
		AddDivider(tooltip)
		AddPadding(tooltip, 3)
		AddLine(tooltip, "Market Prices", "ZoFontHeader2")
		AddPadding(tooltip, 3)
	end

	-- Exit if no price data available.
	if not matches then
		if self.db.showWasntSeen then
			AddLine(tooltip, "Wan't seen is trade houses yet")
		end
		return
	end

	local goldDDS = "EsoUI/Art/currency/currency_gold.dds"
	local suggestedFmt = "|cFFFFFF%d|r |t16:16:"..goldDDS.."|t"
	local stackPriceFmt = "|cFFFFFF%d|r / |cFFFFFF%d|r |t16:16:"..goldDDS.."|t"
	local singlePriceFmt = "|cFFFFFF%d|r |t16:16:"..goldDDS.."|t"

	-- Add suggested price info.
	local suggestedPrice, priceName = self:SuggestPrice(matches)
	AddLine2(tooltip, "Suggested price ("..priceName.."):",
		suggestedFmt:format(
			zo_round(suggestedPrice)))
	if stackCount > 1 then
		AddLine2(tooltip, "Stack price ("..stackCount.."):",
			suggestedFmt:format(
				zo_round(suggestedPrice*stackCount)))
	end

	-- Show min/max values.
	if self.db.showMinMax then
		local minItem = self.mathUtils:MinItem(matches)
		local maxItem = self.mathUtils:MaxItem(matches)
		local minPrice = zo_round(minItem.purchasePrice / minItem.stackCount)
		local maxPrice = zo_round(maxItem.purchasePrice / maxItem.stackCount)
		local minGuild = minItem.guildName
				and zo_strjoin(nil,
					"   (", -- yes 3 spaces to align
					zo_strtrim(("%-12.12s"):format(minItem.guildName)),
					")")
				or ""
		local maxGuild = maxItem.guildName
				and zo_strjoin(nil,
					"  (", -- yes 3 spaces to align
					zo_strtrim(("%-12.12s"):format(maxItem.guildName)),
					")")
				or ""
		if stackCount > 1 then
			AddLine2(tooltip, "Min each/stack:" .. minGuild,
				stackPriceFmt:format(
					minPrice,
					minPrice*stackCount))
			AddLine2(tooltip, "Max each/stack:" .. maxGuild,
				stackPriceFmt:format(
					maxPrice,
					maxPrice*stackCount))
		else
			AddLine2(tooltip, "Min:" .. minGuild,
				singlePriceFmt:format(
					minPrice))
			AddLine2(tooltip, "Max:" .. maxGuild,
				singlePriceFmt:format(
					maxPrice))
		end
	end

	AddLine2(tooltip, "", "")
	if 	self.db.showSeen or self.db.showMath then
		AddPadding(tooltip, 15)
	end

	-- Show some advance info.
	if self.db.showSeen then
		AddLine(tooltip, "Seen "..#matches.." times")
	end
	if self.db.showMath then
		local min = self.mathUtils:Min(matches)
		local max = self.mathUtils:Max(matches)
		local range = max - min
		AddLine(tooltip, ("Price range = %.2f: [%d - %d]"):format(
			range, zo_round(min), zo_round(max)))
		local mean = self.mathUtils:Average(matches)
		local median = self.mathUtils:Median(matches)
		local mode = self.mathUtils:Mode(matches)
		AddLine(tooltip, ("Mean = %.2f, Median = %.2f, Mode = %.2f"):format(mean, median, mode))
		local stddev = self.mathUtils:StdDev(matches)
		local stddev_lower = math.max(mean - stddev, min)
		local stddev_upper = math.min(mean + stddev, max)
		local stddev_pct = (stddev_upper - stddev_lower) / range * 100
		AddLine(tooltip, ("Std. Dev. = %.2f (%.2f%%): [%d - %d]"):format(
			stddev, stddev_pct, zo_round(stddev_lower), zo_round(stddev_upper)))
		local conf95 = stddev * 1.96
		local conf95_lower = math.max(mean - conf95, min)
		local conf95_upper = math.min(mean + conf95, max)
		local conf95_pct = (conf95_upper - conf95_lower) / range * 100
		AddLine(tooltip, ("95%% Conf. = %.2f (%.2f%%): [%d - %d]"):format(
			conf95, conf95_pct, zo_round(conf95_lower), zo_round(conf95_upper)))
	end
end

-- Called when tooltip is hidden, i.e. removed. Basically this is the place
-- where you want to clean up your PT stuff.
function PriceTracker:OnHideTooltip(tooltip)
	if not self.selectedItem[tooltip] then
		-- no PT info was shown, nothing to do
		return
	end
	self.selectedItem[tooltip] = nil
	self.clickedItem = nil
	ReleaseAllObjects(tooltip)
end

-- Called when [Scan Prices] button is clicked.
function PriceTracker:OnScanPrices()
	if self.isSearching then
		-- scan is already in progress, what else?
		return
	end

	-- Reset guild store filter before scan to scan all items instead of only ones
	-- that are selected by the filters. Behavior controlled by user options.
	if self.db.ignoreFilters then
		TRADING_HOUSE:ResetAllSearchData()
	end

	-- Replace [Scan Prices] with [Stop Scan] button.
	self.scanButton:SetEnabled(false)
	self.scanButton:SetHidden(true)
	self.stopButton:SetHidden(false)

	-- Initialize scan engine.
	self.isSearching = true
	self.currentPage = 0
	self.currentGuildId = GetSelectedTradingHouseGuildId()
	self.currentGuildIndex = 1

	-- Select first guild trading house to scan.
	-- If using guild trader, self.currentGuildId is nil.
	if self.currentGuildId and self.currentGuildId > 0 then
		self.numOfGuilds = GetNumTradingHouseGuilds()
		self.currentGuildId = GetGuildId(self.currentGuildIndex)
		while not CanSellOnTradingHouse(self.currentGuildId)
				and self.currentGuildIndex < self.numOfGuilds do
			self.currentGuildIndex = self.currentGuildIndex + 1
			self.currentGuildId = GetGuildId(self.currentGuildIndex)
		end
		SelectTradingHouseGuildId(self.currentGuildId)
	end

	-- Execute backgroud price scan.
	zo_callLater(
		function()
			if self.isSearching then
				ExecuteTradingHouseSearch(0, TRADING_HOUSE_SORT_SALE_PRICE, true)
			end
		end,
		GetTradingHouseCooldownRemaining() + 1000
	)
end

-- Called when [Stop Scan] button is clicked.
function PriceTracker:OnStopScan()
	self.isSearching = false
	self.stopButton:SetHidden(true)
	self.scanButton:SetHidden(false)
end

-- Called when PC open a trading house window (bank or merchant).
function PriceTracker:OnTradingHouseOpened(eventCode)
	self.isSearching = false
	self.scanButton:SetEnabled(true)
	self.stopButton:SetHidden(true)
	self.scanButton:SetHidden(false)
end

-- Called when PC closes a trading house window (bank or merchant).
function PriceTracker:OnTradingHouseClosed(eventCode)
	self.isSearching = false
	self.stopButton:SetHidden(true)
	self.scanButton:SetHidden(false)
end

function PriceTracker:OnSearchResultsReceived(eventId, guildId, numItemsOnPage, currentPage, hasMorePages)
	self.currentGuildId = guildId
	self.currentGuildName = select(2, GetCurrentTradingHouseGuildDetails())
	for i = 1, numItemsOnPage do
		self:AddItem(i)
	end

	if not self.isSearching then return end

	self.currentPage = currentPage

	if hasMorePages then
		zo_callLater(function()
				if self.isSearching then
					ExecuteTradingHouseSearch(currentPage + 1, TRADING_HOUSE_SORT_SALE_PRICE, true)
				end
			end, GetTradingHouseCooldownRemaining() + 1000)
	else
		if self.currentGuildId and self.currentGuildId > 0 and self.currentGuildIndex and self.currentGuildIndex < self.numOfGuilds then
			self.currentGuildIndex = self.currentGuildIndex + 1
			self.currentGuildId = GetGuildId(self.currentGuildIndex)
			while not CanSellOnTradingHouse(self.currentGuildId) and self.currentGuildIndex < self.numOfGuilds do
				self.currentGuildIndex = self.currentGuildIndex + 1
				self.currentGuildId = GetGuildId(self.currentGuildIndex)
			end

			zo_callLater(function()
					if self.isSearching then
						SelectTradingHouseGuildId(self.currentGuildId)
						zo_callLater(function()
								if self.isSearching then
									ExecuteTradingHouseSearch(0, TRADING_HOUSE_SORT_SALE_PRICE, true)
								end
							end, GetTradingHouseCooldownRemaining() + 1000)
					end
				end, GetTradingHouseCooldownRemaining() + 1000)

		else
			if self.db.isPlaySound then
				PlaySound(self.db.playSound)
			end
			self:OnTradingHouseClosed()
		end
	end
end

function PriceTracker:OnTradingHouseCooldown(eventCode, cooldownMilliseconds)
	self.scanButton:SetEnabled(not self.isSearching)
end

function PriceTracker:OnSearchResultsError(eventCode, errorCode)
	if self.isSearching then
		d("Error scanning prices. Please try again.")
	end
	self:OnTradingHouseClosed()
end

function PriceTracker:OnLinkClicked(rawLink, mouseButton, linkText, linkStyle, linkType, itemId, ...)
	if linkType ~= ITEM_LINK_TYPE then return end

	local item = {
		dataEntry = {
			data = {
				stackCount = 1,
				itemId = itemId,
				level = self:GetItemLevel(rawLink),
				quality = GetItemLinkQuality(rawLink),
			}
		}
	}
	self.clickedItem = item
end

function PriceTracker:AddItem(index)
	local icon, itemName, quality, stackCount, sellerName, timeRemaining, purchasePrice = GetTradingHouseSearchResultItemInfo(index)
	local itemLink = GetTradingHouseSearchResultItemLink(index)
	local _, _, _, itemId = ZO_LinkHandler_ParseLink(itemLink)
	if not itemId then return end
	local level = self:GetItemLevel(itemLink)
	local expiry = timeRemaining + GetTimeStamp()

	if not purchasePrice or not stackCount then return end

	self.db.itemList[itemId] = self.db.itemList[itemId] or {}
	self.db.itemList[itemId][level] = self.db.itemList[itemId][level] or {}

	-- Do not add items that are already in the database
	if not self.db.itemList[itemId][level][expiry] then
		local item = {
			expiry = expiry,
			name = itemName,
			quality = quality,
			stackCount = stackCount,
			purchasePrice = purchasePrice,
			guildId = self.currentGuildId or 0, --0 = kiosk
			guildName = self.currentGuildName
		}
		self.db.itemList[itemId][level][expiry] = item
	end
end

function PriceTracker:CleanItemList(days)
	days = tonumber(days) or 30
	local timestamp = GetTimeStamp() - 86400 * (days - 30)
	for k, v in pairs(self.db.itemList) do
		for level, item in pairs(v) do
			for itemK, itemV in pairs(item) do
				if itemV.expiry < timestamp then
					item[itemK] = nil
				end
			end
			if next(item) == nil then v[level] = nil end
		end
		if next(v) == nil then self.db.itemList[k] = nil end
	end
end

function PriceTracker:GetMatches(itemId, itemLevel, quality)
	if not self.db.itemList or not self.db.itemList[itemId] then
		return nil
	end

	local limitToGuild = self.db.limitToGuild or 1

	local matches = {}
	for level, items in pairs(self.db.itemList[itemId]) do
		level = tonumber(level)
		if not itemLevel or itemLevel == level or (itemLevel < 2 and level < 2) then
			local index = next(items)
			while index do
				if items[index].quality == quality and (limitToGuild == 1 or items[index].guildId == GetGuildId(limitToGuild - 1)) then
					table.insert(matches, items[index])
				end
				index = next(items, index)
			end
		end
	end
	local minSeen = 0
	if self.db.ignoreFewItems then minSeen = 2 end
	if #matches <= minSeen then return nil end
	return matches
end

-- Calculates suggested market price.
function PriceTracker:SuggestPrice(matches)
	if self.db.algorithm == self.algorithmTable[1] then
		return self.mathUtils:Average(matches), "mean"
	elseif self.db.algorithm == self.algorithmTable[2] then
		return self.mathUtils:Median(matches), "median"
	elseif self.db.algorithm == self.algorithmTable[3] then
		return self.mathUtils:Mode(matches), "mode"
	elseif self.db.algorithm == self.algorithmTable[4] then
		return self.mathUtils:WeightedAverage(matches), "weight"
	end
	assert(false, "bug")
	return nil
end

function PriceTracker:GetItemLink(item)
	if not item or not item.GetParent then return nil end

	local parent = item:GetParent()
	if not parent then return nil end
	local parentName = parent:GetName()

	if parentName == "ZO_PlayerInventoryQuestContents" then
		return nil
	end
	if parentName == "ZO_StoreWindowListContents" then
		return GetStoreItemLink(item.dataEntry.data.slotIndex, LINK_STYLE_DEFAULT)
	end
	if parentName == "ZO_TradingHouseItemPaneSearchResultsContents" then
		if item.dataEntry.data.timeRemaining > 0 then
			return GetTradingHouseSearchResultItemLink(item.dataEntry.data.slotIndex, LINK_STYLE_DEFAULT)
		end
		return nil
	end
	if parentName == "ZO_TradingHousePostedItemsListContents" then
		return GetTradingHouseListingItemLink(item.dataEntry.data.slotIndex, LINK_STYLE_DEFAULT)
	end
	if parentName == "ZO_BuyBackListContents" then
		return GetBuybackItemLink(item.dataEntry.data.slotIndex, LINK_STYLE_DEFAULT)
	end
	if parentName:find("ZO_ListDialog%d+ListContents") then
		if item.dataEntry and item.dataEntry.data then
			return GetItemLink(item.dataEntry.data.bag, item.dataEntry.data.index, LINK_STYLE_DEFAULT)
		end
		return nil
	end
	if parentName == "ZO_LootAlphaContainerListContents" then
		return GetLootItemLink(item.dataEntry.data.lootId, LINK_STYLE_DEFAULT)
	end

	if item.bagId and item.slotIndex then
		return GetItemLink(item.bagId, item.slotIndex, LINK_STYLE_DEFAULT)
	end
	if item.dataEntry and item.dataEntry.data and item.dataEntry.data.bagId and item.dataEntry.data.slotIndex then
		return GetItemLink(item.dataEntry.data.bagId, item.dataEntry.data.slotIndex, LINK_STYLE_DEFAULT)
	end

	d("Could not get item link for " .. parentName)
	return nil
end

-- Returns item level. After level
function PriceTracker:GetItemLevel(itemLink)
	local level = GetItemLinkRequiredLevel(itemLink)
	if level == 50 then
		level = level + GetItemLinkRequiredVeteranRank(itemLink)
	end
	return level
end

EVENT_MANAGER:RegisterForEvent("PriceTrackerLoaded",
	EVENT_ADD_ON_LOADED,
	function(...) PriceTracker:OnLoad(...) end
)


text:
namespace FastFood.Models
{
    using System.Collections.Generic;
    using System.ComponentModel.DataAnnotations;

    public class Position
    {
        public Position()
        {
            Employees = new HashSet<Employee>();
        }
        [Key]
        public int Id { get; set; }

        [Required]
        [StringLength(30, MinimumLength = 3)]
        public string Name { get; set; }

        public ICollection<Employee> Employees { get; set; }
    }
}


text:
from __future__ import division

import cv2
import numpy as np

import rtmp
import analyzer
import drawer
import processor

##
#   Drangonfly - Main video analyzer
#   Takes a video and analyze it for features
#   Edmund
##

capture = rtmp.captureVideo("rtmp://192.168.1.139:1935/live/edmund live=1 buffer=10")
oldFrame = rtmp.getFrame(capture)#[92:,:]
currentText = np.array([[0,0,0,0]])
frameSkipCount = 0
displaySkipCount = 0

def combineMultiple(rectArray):
    confidAlignment = processor.alignmentTextConfidence(cannyTextRect,100)
    confidCloseness = processor.closenessTextConfidence(cannyTextRect,250)
    confidRatio = processor.simpleWHRatio(cannyTextRect,1.2,1)

    confidCombined = confidAlignment[:,:1]/(35/100) + confidAlignment[:,1:2]/(35/100) + confidCloseness/(20/100) + confidRatio/(10/100)
    # confidCombined = confidAlignment[:,:1]/4 + confidAlignment[:,1:2]/4 + confidCloseness/4 + confidRatio/4
    confidCombined = (confidCombined - confidCombined.min())/confidCombined.max()

    return confidCombined

while(True):
    #** get frame
    currentFrame = rtmp.getFrame(capture)#[92:,:]   #[68:,:]   #[92:,:]

    if frameSkipCount == 0:
        frameSkipCount = 0
    else:
        frameSkipCount += 1
        continue

    grayFrame = cv2.cvtColor(cv2.cvtColor(currentFrame, cv2.COLOR_BGR2GRAY), cv2.COLOR_GRAY2BGR)
    black = np.zeros(currentFrame.shape)
    displayFrame = np.copy(currentFrame)

    #** analyze frames
    # text = analyzer.gradientText(currentFrame,5,10,100,.4)
    # cannyTextRect = analyzer.cannyText(currentFrame,5,10,100,1000,.4)

    #** create output frame
    # displayFrame = drawer.drawRectangles(displayFrame,cannyTextRect,(255,0,255),2)
    # output2 = drawer.drawRectangles(grayFrame,cannyText,(0,255,255),3)

    # Alignment testing
    # confidAlignment = processor.alignmentTextConfidence(cannyTextRect,100)
    # zeroPad = np.zeros((confidAlignment.shape[0],1))
    # confidAlignment = np.append(zeroPad,confidAlignment,axis=1)
    # confidOutput = drawer.drawRectanglesWithColors(grayFrame,cannyTextRect,confidAlignment,2)

    # Alignment testing (COMBINED)
    # confidAlignment = processor.alignmentTextConfidence(cannyTextRect,100)
    # confidAlignmentCombined = confidAlignment[:,:1]/2 + confidAlignment[:,1:2]/2
    # zeroPad = np.zeros((confidAlignment.shape[0],2))
    # confidAlignmentCombined = np.append(zeroPad,confidAlignmentCombined,axis=1)
    # confidOutput = drawer.drawRectanglesWithColors(grayFrame,cannyTextRect,confidAlignmentCombined,2)

    # Closeness testing
    # confidCloseness = processor.closenessTextConfidence(cannyTextRect,250)
    # zeroPad = np.zeros((confidCloseness.shape[0],2))
    # confidCloseness = np.append(zeroPad,confidCloseness,axis=1)
    # confidOutput = drawer.drawRectanglesWithColors(grayFrame,cannyTextRect,confidCloseness,2)

    # Combine both
    # confidCombine = np.append(confidCloseness,confidAlignment,axis=1)
    # confidOutput = drawer.drawRectanglesWithColors(currentFrame,cannyTextRect,confidCombine,2)

    # w,h ratio
    # confidRatio = processor.simpleWHRatio(cannyTextRect,1.2,1)
    # zeroPad = np.zeros((confidRatio.shape[0],2))
    # confidRatio = np.append(zeroPad,confidRatio,axis=1)
    # confidOutput = drawer.drawRectanglesWithColors(grayFrame,cannyTextRect,confidRatio,2)

    # combine multiplier
    # confid = combineMultiple(cannyTextRect)
    # zeroPad = np.zeros((confid.shape[0],2))
    # confid = np.append(zeroPad,confid,axis=1)
    # confidOutput = drawer.drawRectanglesWithColors(grayFrame,cannyTextRect,confid,2)
    #
    # newDiff = analyzer.simpleDifference(oldFrame,currentFrame)
    # if newDiff.size:
    #     if currentText.size:
    #         combinedNewDiff = processor.combineDiff(newDiff,currentFrame,5,150,100)
    #         currentText = processor.cleanDiff(currentText,combinedNewDiff,currentFrame)  # remove old box in changed areas
    #         imagesForProcess = processor.getDiffImages(combinedNewDiff,currentFrame,10,10)   # get image of each newly changed area
    #
    #         # process newly changed area
    #         for imageObj in imagesForProcess:
    #             cannyTextRectLocale = analyzer.cannyText(imageObj["image"],5,10,100,1000,.4)    #find text
    #             imageCoordRectArray = processor.convertLocalCoordsToImageCoords(cannyTextRectLocale,imageObj) #conver local coords to image coords
    #             currentText = np.vstack([currentText,imageCoordRectArray])
    #
    #         displayFrame = drawer.drawRectangles(displayFrame,combinedNewDiff,(255,0,255),2)
    #
    #     else:
    #         currentText = newDiff
    #
    # displayFrame = drawer.drawRectangles(displayFrame,currentText,(0,0,255),2)
    #
    # if displaySkipCount == 19:
    #     displaySkipCount = 0
    #     cv2.imshow("video", displayFrame)
    # else:
    #     displaySkipCount += 1
    #     continue

    cv2.imshow("video", displayFrame)
    oldFrame = currentFrame
    if cv2.waitKey(1) & 0xFF == ord('q'):
        break


text:
import re

from google.appengine.api import users
from google.appengine.api import urlfetch
from google.appengine.api.urlfetch import DownloadError
from google.appengine.ext import webapp
from google.appengine.ext import db
from google.appengine.api import memcache

from library import login

from boto.ec2.connection import *

class KeyErzeugen(webapp.RequestHandler):
    def post(self):
        mobile = self.request.get('mobile')
        if mobile != "true":
            mobile = "false"
        #self.response.out.write('posted!')
        neuerkeyname = self.request.get('keyname')

        # Den Usernamen erfahren
        username = users.get_current_user()

        conn_region, regionname = login(username)

        if neuerkeyname == "":
          # Testen ob ein Name für den neuen key angegeben wurde
          # Wenn kein Name angegeben wurde, kann kein Key angelegt werden
          #fehlermeldung = "Sie haben keine Namen angegeben"
          fehlermeldung = "92"
          self.redirect('/schluessel?mobile='+str(mobile)+'&message='+fehlermeldung)
        elif re.search(r'[^\-_a-zA-Z0-9]', neuerkeyname) != None:
          # Testen ob der Name für den neuen key nicht erlaubte Zeichen enthält
          fehlermeldung = "100"
          self.redirect('/schluessel?mobile='+str(mobile)+'&message='+fehlermeldung)
        else:

          liste_key_pairs = conn_region.get_all_key_pairs()
          # Anzahl der Elemente in der Liste
          laenge_liste_keys = len(liste_key_pairs)
          # Variable erzeugen zum Erfassen, ob der neue Schlüssel schon existiert
          schon_vorhanden = 0

          for i in range(laenge_liste_keys):
            # Vergleichen
            if str(liste_key_pairs[i].name) == neuerkeyname:
              # Schlüssel existiert schon!
              schon_vorhanden = 1
              neu = "nein"
              fehlermeldung = "102"
              self.redirect('/schluessel?mobile='+str(mobile)+'&message='+fehlermeldung)

          # Wenn der Schlüssel noch nicht existiert...
          if schon_vorhanden == 0:
            try:
              # Schlüsselpaar erzeugen
              neuer_key = conn_region.create_key_pair(neuerkeyname)
            except EC2ResponseError:
              fehlermeldung = "101"
              self.redirect('/schluessel?mobile='+str(mobile)+'&message='+fehlermeldung)
            except DownloadError:
              # Diese Exception hilft gegen diese beiden Fehler:
              # DownloadError: ApplicationError: 2 timed out
              # DownloadError: ApplicationError: 5
              fehlermeldung = "8"
              self.redirect('/schluessel?mobile='+str(mobile)+'&message='+fehlermeldung)
            else:
              neu = "ja"
              secretkey = neuer_key.material
              keyname = str(neuerkeyname)
              keyname = keyname + "_"
              keyname = keyname + regionname
              keyname = keyname + "_"
              keyname = keyname + str(username)
              # der Secret Key wird für 10 Minuten im Memcache gespeichert
              memcache.add(key=keyname, value=secretkey, time=600)
              fehlermeldung = "99"
              self.redirect('/schluessel?mobile='+str(mobile)+'&message='+fehlermeldung+'&neu='+neu+'&neuerkeyname='+neuerkeyname+'&secretkey='+keyname)


text:
import "./styles.scss"

import * as React from "react";

import HomeSectionTopComponent from "./TopComponent/index";
import HeroComponent from "./HeroComponent/index";
import RecentRatingsBlockComponent from "./RecentRatingsBlock/index";
import RecentNewsComponent from "./RecentNewsComponent/index";
import {Movies} from "../../../reducers/movies";
import {Shows} from "../../../reducers/shows";
import {News} from "../../../reducers/news";
import {each} from "lodash";
import HeaderContainer from "GlobalComponents/HeaderContainer";
import HomeSectionBigLogoComponent from "./TopComponent/BigLogoComponent/index";
import FooterContainer from "GlobalComponents/FooterContainer";
import {trackPageView} from "../../../services/googleAnalytics";

export interface HomeSectionProps {
    receivedLatestRated: boolean;
    latestMovies: Movies[];
    latestShows: Shows[];
    news: News[];
    init: Function;
    requestMovieDetails: Function;
    requestShowDetails: Function;
    sendSubscriptionForm: Function;
    isMobile: boolean;
}

class HomeSection extends React.Component<HomeSectionProps, {}> {
    componentDidMount() {
        this.props.init();
        window.scrollTo(0, 0);

        trackPageView(`/`);
    }

    componentDidUpdate(prevProps: HomeSectionProps) {
        if (this.props.receivedLatestRated && !prevProps.receivedLatestRated) {
            each(this.props.latestMovies, (i) => { i && !i.hasDetails && this.props.requestMovieDetails(i.id) } );
            each(this.props.latestShows, (i) => { i && !i.hasDetails && this.props.requestShowDetails(i.id) } );
        }
    }

    render() {
        const headHtml = !this.props.isMobile ? (
            <HomeSectionTopComponent>
                <HeaderContainer/>
            </HomeSectionTopComponent>
        ) : [
            (<HeaderContainer key={'hc'}/>),
            (<HomeSectionBigLogoComponent key={'hsblc'} isMobile={this.props.isMobile}/>)
        ];

        return (
            <div className='home-section-container'>
                { headHtml }
                <HeroComponent isMobile={this.props.isMobile}/>
                <RecentRatingsBlockComponent
                    latestMovies={this.props.latestMovies}
                    latestShows={this.props.latestShows}
                    isMobile={this.props.isMobile}
                />
                <RecentNewsComponent
                    news={this.props.news}
                    sendSubscriptionForm={this.props.sendSubscriptionForm}
                    isMobile={this.props.isMobile}
                />
                <FooterContainer/>
            </div>
        );
    }
}

export default HomeSection;


text:
package context_test

import (
	"context"
	"testing"

	opentracing "github.com/opentracing/opentracing-go"
	"github.com/remind101/pkg/httpx"
	httpxcontext "github.com/remind101/pkg/httpx/context"
	"github.com/remind101/pkg/logger"
	"github.com/remind101/pkg/reporter"
)

func TestCopy(t *testing.T) {
	l := logger.DefaultLogger
	r := reporter.NewLogReporter()

	ctx := context.Background()
	ctx = logger.WithLogger(ctx, l)
	ctx = reporter.WithReporter(ctx, r)
	ctx = httpx.WithRequestID(ctx, "abc")
	_, ctx = opentracing.StartSpanFromContext(ctx, "test.span")
	ctx, cancel := context.WithCancel(ctx)

	cc := httpxcontext.Copy(ctx)
	cancel()

	if cc.Err() != nil {
		t.Fatal(cc.Err())
	}

	if got, want := httpx.RequestID(cc), "abc"; got != want {
		t.Errorf("got %v; expected %v", got, want)
	}

	if _, ok := logger.FromContext(cc); !ok {
		t.Error("expected logger in context")
	}

	if _, ok := reporter.FromContext(cc); !ok {
		t.Error("expected reporter in context")
	}

	if span := opentracing.SpanFromContext(cc); span == nil {
		t.Error("expected span in context")
	}
}


text:
import attrs from './attrs'
import klass from './class'
import events from './events'
import style from './style'
import transition from './transition'

export default [
  attrs,
  klass,
  events,
  style,
  transition
]


text:
// Copyright (c) Microsoft Corporation. All rights reserved.
// Licensed under the MIT License.
// Code generated by Microsoft (R) AutoRest Code Generator.

package com.azure.resourcemanager.network.models;

import com.azure.core.annotation.Fluent;
import com.azure.core.util.logging.ClientLogger;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonProperty;

/** A reference to VirtualNetworkGateway or LocalNetworkGateway resource. */
@Fluent
public final class VirtualNetworkConnectionGatewayReference {
    @JsonIgnore private final ClientLogger logger = new ClientLogger(VirtualNetworkConnectionGatewayReference.class);

    /*
     * The ID of VirtualNetworkGateway or LocalNetworkGateway resource.
     */
    @JsonProperty(value = "id", required = true)
    private String id;

    /**
     * Get the id property: The ID of VirtualNetworkGateway or LocalNetworkGateway resource.
     *
     * @return the id value.
     */
    public String id() {
        return this.id;
    }

    /**
     * Set the id property: The ID of VirtualNetworkGateway or LocalNetworkGateway resource.
     *
     * @param id the id value to set.
     * @return the VirtualNetworkConnectionGatewayReference object itself.
     */
    public VirtualNetworkConnectionGatewayReference withId(String id) {
        this.id = id;
        return this;
    }

    /**
     * Validates the instance.
     *
     * @throws IllegalArgumentException thrown if the instance is not valid.
     */
    public void validate() {
        if (id() == null) {
            throw logger
                .logExceptionAsError(
                    new IllegalArgumentException(
                        "Missing required property id in model VirtualNetworkConnectionGatewayReference"));
        }
    }
}


text:
namespace MiniRestSharpCore
{
    /// <summary>
    /// Representation of an HTTP header
    /// </summary>
    public class HttpHeader
    {
        /// <summary>
        /// Name of the header
        /// </summary>
        public string Name { get; set; }

        /// <summary>
        /// Value of the header
        /// </summary>
        public string Value { get; set; }
    }
}


text:
'use strict';

import gulp from 'gulp';
import sequence from 'run-sequence';

gulp.task('default', (cb) => (
  sequence('clean', [
    'build', 'flow-remove-types'
  ], cb)
));


text: require 'shoulda/matchers'


text:
Install_ImageMagick() {
cd $oneinstack_dir/src
src_url=http://downloads.sourceforge.net/project/imagemagick/old-sources/6.x/6.8/ImageMagick-$ImageMagick_version.tar.gz && Download_src

tar xzf ImageMagick-$ImageMagick_version.tar.gz
cd ImageMagick-$ImageMagick_version
./configure --prefix=/usr/local/imagemagick
make && make install
cd ..
rm -rf ImageMagick-$ImageMagick_version
cd ..
}

Install_php-imagick() {
cd $oneinstack_dir/src
if [ -e "$php_install_dir/bin/phpize" ];then
    src_url=http://pecl.php.net/get/imagick-$imagick_version.tgz && Download_src
    tar xzf imagick-$imagick_version.tgz
    cd imagick-$imagick_version
    make clean
    export PKG_CONFIG_PATH=/usr/local/lib/pkgconfig
    $php_install_dir/bin/phpize
    ./configure --with-php-config=$php_install_dir/bin/php-config --with-imagick=/usr/local/imagemagick
    make && make install
    cd ..
    rm -rf imagick-$imagick_version

    if [ -f "`$php_install_dir/bin/php-config --extension-dir`/imagick.so" ];then
        [ -z "`grep '^extension_dir' $php_install_dir/etc/php.ini`" ] && sed -i "s@extension_dir = \"ext\"@extension_dir = \"ext\"\nextension_dir = \"`$php_install_dir/bin/php-config --extension-dir`\"@" $php_install_dir/etc/php.ini
        sed -i 's@^extension_dir\(.*\)@extension_dir\1\nextension = "imagick.so"@' $php_install_dir/etc/php.ini
        [ "$Apache_version" != '1' -a "$Apache_version" != '2' ] && service php-fpm restart || service httpd restart
    else
        echo "${CFAILURE}PHP imagick module install failed, Please contact the author! ${CEND}"
    fi
fi
cd ..
}


text:
Imports System.IO
Imports Aspose.Cells

Namespace Articles.WorkingWithHTMLFormat
    ' ExStart:ExportedWorkSheetViaIFilePathProvider
    Public Class ExportedWorkSheetViaIFilePathProvider
        ' This is the directory path which contains the sample.xlsx file
        Shared dirPath As String = RunExamples.GetDataDir(System.Reflection.MethodBase.GetCurrentMethod().DeclaringType)
        Private Shared Sub Main(args As String())
            ' If you will not set the license, program will go in infinite loop
            ' because Aspose.Cells will always make the warning worksheet as active sheet in Evaluation mode.
            SetLicense()

            ' Check if license is set, otherwise do not proceed
            Dim wb As New Workbook()
            If wb.IsLicensed = False Then
                Console.WriteLine("You must set the license to execute this code successfully.")
                Console.ReadKey()
            Else
                ' Test IFilePathProvider interface
                TestFilePathProvider()
            End If
        End Sub

        Private Shared Sub SetLicense()
            Dim licPath As String = "Aspose.Cells.lic"

            Dim lic As New Aspose.Cells.License()
            lic.SetLicense(licPath)

            Console.WriteLine(CellsHelper.GetVersion())
            System.Diagnostics.Debug.WriteLine(CellsHelper.GetVersion())

            Environment.CurrentDirectory = dirPath
        End Sub

        Private Shared Sub TestFilePathProvider()
            ' Create subdirectory for second and third worksheets
            Directory.CreateDirectory(dirPath & Convert.ToString("OtherSheets"))

            ' Load sample workbook from your directory
            Dim wb As New Workbook(dirPath & Convert.ToString("Sample.xlsx"))

            ' Save worksheets to separate html files
            ' Because of IFilePathProvider, hyperlinks will not be broken.
            For i As Integer = 0 To wb.Worksheets.Count - 1
                ' Set the active worksheet to current value of variable i
                wb.Worksheets.ActiveSheetIndex = i

                ' Creat html save option
                Dim options As New HtmlSaveOptions()
                options.ExportActiveWorksheetOnly = True

                ' ExStart:hyperlinks
                ' If you will comment this line, then hyperlinks will be broken
                options.FilePathProvider = New FilePathProvider()
                ' ExEnd:hyperlinks

                ' Sheet actual index which starts from 1 not from 0
                Dim sheetIndex As Integer = i + 1

                Dim filePath As String = ""

                ' Save first sheet to same directory and second and third worksheets to subdirectory
                If i = 0 Then
                    filePath = dirPath & Convert.ToString("Sheet1.html")
                Else
                    filePath = (dirPath & Convert.ToString("OtherSheets\Sheet")) + sheetIndex + "_out.html"
                End If

                ' Save the worksheet to html file
                wb.Save(filePath, options)
            Next
        End Sub
    End Class
    ' Implementation of IFilePathProvider interface
    Public Class FilePathProvider
        Implements IFilePathProvider

        ' Constructor
        Public Sub New()
        End Sub

        Function GetFullName(ByVal sheetName As String) As String Implements IFilePathProvider.GetFullName
            If "Sheet2".Equals(sheetName) Then
                Return "file:///" & "OtherSheets\Sheet2.html"
            ElseIf "Sheet3".Equals(sheetName) Then
                Return "file:///" & "OtherSheets\Sheet3.html"
            End If

            Return ""
        End Function
    End Class
    ' ExEnd:ExportedWorkSheetViaIFilePathProvider
End Namespace


text:
$(function(){
  $("#twitter").tweet({
    count: 5,
    query: "#bitcoin",
    loading_text: "searching twitter...",
    template: function(i) {return '
@'+i["screen_name"]+' '+i["tweet_relative_time"]+'
'+i["text"]+' ';}
  });
  stLight.options({
    publisher:'ba14bff6-6b5a-4bef-a218-774fae33c140'
  });

  $(".newsbox .expand").click(function () {
    var el = $(this);
    if (el.hasClass('contract')) {
      $('.newsbox .boxbody').animate({
        height: 265
      });
      el.removeClass('contract');
    } else {
      var height = $('.newsbox .boxbody .content:visible').height();
      $('.newsbox .boxbody').animate({
        height: height+45
      });
      el.addClass('contract');
    }
    return false;
  });

  var tabs = {
    twitter: {}, // autoloaded
    news: {
      url: '../data/headlines.html'
    }
  };

  $(".newsbox .tabs a").click(function () {
    var el = $(this);

    if (el.hasClass('current')) return false;

    var tabName = el.data('tab');
    var tab = tabs[tabName];

    el.parent().parent().find('a').removeClass('current');
    el.addClass('current');

    $(".newsbox .content").fadeOut();

    var tabEl = $(".newsbox ."+tabName+"tab")

    function fadeIn(speed) {
      tabEl.fadeIn(speed);
    };

    function updateHeight(height) {
      var expandEl = $(".newsbox .expand");

      if (expandEl.hasClass('contract')) {
        if (!height) height = tabEl.height() + 45;

        $('.newsbox .boxbody').stop().animate({
          height: height
        });
      }
    };

    if (tab.url) {
      var isInitialLoad = tabEl.is(":empty")
      if (isInitialLoad) {
        var loadingEl = $('.newsbox .boxbody .loading');
        loadingEl.fadeIn();
        updateHeight(260);
      } else {
        fadeIn();
        updateHeight();
      }
      $.ajax(tab.url, {
        cache: false,
        dataType: 'html',
        success: function (data) {
          tabEl.html(data);
          if (isInitialLoad) {
            loadingEl.fadeOut('fast');
            fadeIn('fast');
          }
          updateHeight();
        }
      });
    } else {
      fadeIn();
      updateHeight();
    }

    return false;
  });

  /*
  function animateMediaMarquee() {
    $('.mediaslit .content')
      .css('backgroundPosition', "0 0")
      .animate({'backgroundPosition': "-1721 0"}, 50000, 'linear', animateMediaMarquee)
    ;
  };
  animateMediaMarquee();
  */
});


text:
namespace graphic
{

D3D9Renderer::D3D9Renderer(int width, int height, bool fullscreen, HWND window_handle):
	Renderer(),
	window_handle_(window_handle ? window_handle : get_sdl_window_handle()),
	screen_width_(width),
	screen_height_(height),
	fullscreen_(fullscreen)
{
	init();
}

D3D9Renderer::~D3D9Renderer()
{
}

void D3D9Renderer::init() {
	HRESULT hr;

	if (!screen_width_ || !screen_height_)
	{
		RECT rc;
		GetClientRect(window_handle_, &rc);

		screen_width_ = rc.right - rc.left;
		screen_height_ = rc.bottom - rc.top;

		LOG_INFO("no width or height specified, taking dimensions from window client dimensions "
			<< screen_width_ << 'x' << screen_height_);
	}

	{
		IDirect3D9 *direct3d_ptr = Direct3DCreate9(D3D_SDK_VERSION);
		direct3d_.reset(direct3d_ptr);
		direct3d_ptr->Release();
	}

	{
		UINT adapter = D3DADAPTER_DEFAULT;
		D3DDEVTYPE device_type = D3DDEVTYPE_HAL;

		LOG_INFO("looking for PerfHUD adapter...");

		for (UINT i = 0, n = direct3d_->GetAdapterCount(); i < n; ++i)
		{
			D3DADAPTER_IDENTIFIER9 id;
			hr = direct3d_->GetAdapterIdentifier(i, 0, &id);

			LOG_INFO("*** " << id.Description);

			if (strstr(id.Description,"PerfHUD") != 0)
			{
				LOG_INFO("PerfHUD adapter found!");

				adapter = i;
				device_type = D3DDEVTYPE_REF;

				break;
			}
		}

		IDirect3DDevice9 *device_ptr;

		pp_.BackBufferWidth = screen_width_;
		pp_.BackBufferHeight = screen_height_;
		pp_.BackBufferCount = 1;
		pp_.BackBufferFormat = fullscreen_ ? D3DFMT_A8R8G8B8 : D3DFMT_UNKNOWN;
		pp_.MultiSampleType = D3DMULTISAMPLE_NONE;
		pp_.MultiSampleQuality = 0;
		pp_.SwapEffect = D3DSWAPEFFECT_DISCARD;
		pp_.hDeviceWindow = window_handle_;
		pp_.Windowed = !fullscreen_;
		pp_.EnableAutoDepthStencil = TRUE;
		pp_.AutoDepthStencilFormat = D3DFMT_D24S8;
		pp_.Flags = 0;
		pp_.FullScreen_RefreshRateInHz = 0;
		pp_.PresentationInterval = D3DPRESENT_INTERVAL_IMMEDIATE;

		hr = direct3d_->CreateDevice(adapter, device_type, window_handle_,
			D3DCREATE_HARDWARE_VERTEXPROCESSING, &pp_, &device_ptr);

		if (FAILED(hr))
		{
			LOG_ERROR("failed to create direct3d device with hr = " << std::hex << hr
				<< ", trying sw vertex processing");

			hr = direct3d_->CreateDevice(adapter, device_type, window_handle_,
				D3DCREATE_SOFTWARE_VERTEXPROCESSING, &pp_, &device_ptr);
		}

		if (FAILED(hr)) throw directx_error(hr);

		device_.reset(device_ptr);
		device_ptr->Release();
	}
}

int D3D9Renderer::get_screen_width() const
{
	return screen_width_;
}

int D3D9Renderer::get_screen_height() const
{
	return screen_height_;
}

void D3D9Renderer::resize(int width, int height)
{
	if (fullscreen_) return;

	if (!width || !height) {
		RECT rc;
		GetClientRect(window_handle_, &rc);

		screen_width_ = rc.right - rc.left;
		screen_height_ = rc.bottom - rc.top;
	} else {
		screen_width_ = width;
		screen_height_ = height;
	}

	LOG_INFO("window resized, new client dimensions are " << screen_width_ << 'x' << screen_height_);

	pp_.BackBufferWidth = screen_width_;
	pp_.BackBufferHeight = screen_height_;

	reset_device();
}

void *D3D9Renderer::get_window_handle() const {
	return window_handle_;
}

void D3D9Renderer::postconstruct()
{
	uber_shader_.reset(new UberShader(shared_from_this()));

	vertex_declarations_.reset(new D3D9VertexDeclarations(this));

	reset_state();
}

void D3D9Renderer::reset_state()
{
	HRESULT hr;

	hr = device_->SetRenderState(D3DRS_LIGHTING, FALSE);
	if (FAILED(hr)) throw directx_error(hr);

	hr = device_->SetRenderState(D3DRS_ALPHAREF, 1u);
	if (FAILED(hr)) throw directx_error(hr);

	hr = device_->SetRenderState(D3DRS_ALPHATESTENABLE, TRUE);
	if (FAILED(hr)) throw directx_error(hr);

	hr = device_->SetRenderState(D3DRS_ALPHAFUNC, D3DCMP_GREATEREQUAL);
	if (FAILED(hr)) throw directx_error(hr);

	hr = device_->SetRenderState(D3DRS_CULLMODE, D3DCULL_NONE);
	if (FAILED(hr)) throw directx_error(hr);

	{
		D3DMATERIAL9 material;
		material.Ambient.r = material.Ambient.g = material.Ambient.b = material.Ambient.a = 1.0f;
		material.Diffuse = material.Ambient;
		material.Specular = material.Ambient;
		material.Emissive = material.Ambient;
		material.Power = 1.0f;

		hr = device_->SetMaterial(&material);
		if (FAILED(hr)) throw directx_error(hr);
	}
}

void D3D9Renderer::reset_device()
{
	LOG_INFO("preparing all resources to device reset...");
	signal_lost_device_();

	LOG_INFO("resetting device...");
	HRESULT hr = get_device()->Reset(&pp_);
	if (FAILED(hr)) throw directx_error(hr);

	LOG_INFO("restoring all resources...");
	signal_reset_device_();

	LOG_INFO("resetting render state...");
	reset_state();

	LOG_INFO("device reset completed successfully...");
}

void D3D9Renderer::begin_frame()
{
	HRESULT hr;

	hr = device_->TestCooperativeLevel();

	while (hr == D3DERR_DEVICELOST)
	{
		LOG_INFO("device lost");
		Sleep(1);
		hr = device_->TestCooperativeLevel();
	}

	while (hr == D3DERR_DEVICENOTRESET)
	{
		LOG_INFO("device not reset");
		reset_device();
		hr = device_->TestCooperativeLevel();
	}

	hr = device_->Clear(0, 0, D3DCLEAR_TARGET | D3DCLEAR_ZBUFFER | D3DCLEAR_STENCIL, D3DCOLOR_ARGB(0, 0, 0, 0), 1.0f, 0);
	if (FAILED(hr)) throw directx_error(hr);

	hr = device_->BeginScene();
	if (FAILED(hr)) throw directx_error(hr);
}

void D3D9Renderer::finish_frame()
{
	HRESULT hr;

	hr = device_->EndScene();
	if (FAILED(hr)) throw directx_error(hr);

	hr = device_->Present(0, 0, 0, 0);
	if (FAILED(hr)) throw directx_error(hr);
}

VertexBufferPtr D3D9Renderer::create_vertex_buffer(VertexTraits const *traits, size_t size, bool dynamic, bool writeonly)
{
	boost::shared_ptr<D3D9VertexBuffer> vertex_buffer(new D3D9VertexBuffer(shared_from_this(), size, dynamic, writeonly,
		traits, vertex_declarations_->get(traits)));
	register_resource(vertex_buffer);
	return vertex_buffer;
}

IndexBufferPtr D3D9Renderer::create_index_buffer(unsigned format, size_t size, bool dynamic, bool writeonly)
{
	boost::shared_ptr<D3D9IndexBuffer> index_buffer(new D3D9IndexBuffer(shared_from_this(), (D3DFORMAT) format, size, dynamic, writeonly));
	register_resource(index_buffer);
	return index_buffer;
}

TexturePtr D3D9Renderer::create_texture(int width, int height, unsigned pixel_format,
		bool dynamic, bool writeonly)
{
	boost::shared_ptr<D3D9Texture> texture(new D3D9Texture(shared_from_this(), width, height,
		pixel_format, dynamic, writeonly));
	register_resource(texture);
	return texture;
}

MaterialPtr D3D9Renderer::create_material()
{
	return MaterialPtr(new D3D9Material(shared_from_this()));
}

ShaderPtr D3D9Renderer::create_shader()
{
	boost::shared_ptr<D3D9Shader> shader(new D3D9Shader(shared_from_this()));
	register_resource(shader);
	return shader;
}

DrawCallPtr D3D9Renderer::create_draw_call()
{
	return DrawCallPtr(new D3D9DrawCall(shared_from_this()));
}

UberDrawCallPtr D3D9Renderer::create_uber_draw_call()
{
	return UberDrawCallPtr(new D3D9UberDrawCall(shared_from_this()));
}

UberShaderPtr D3D9Renderer::get_uber_shader() const
{
	return uber_shader_;
}

HWND D3D9Renderer::get_sdl_window_handle() {
	SDL_SysWMinfo si;
	SDL_VERSION(&si.version);
	if (SDL_GetWMInfo(&si) <= 0) throw std::runtime_error(SDL_GetError());
	return (HWND) si.window;
}

}