text:
import sys, os, random, cStringIO, urllib
from budget.model.sysutil import UploadObject
reload(sys)
sys.setdefaultencoding('utf8')
import base64
import sha
from datetime import date, datetime as dt
import traceback, os, smtplib, StringIO, base64, hashlib

from email.MIMEMultipart import MIMEMultipart
from email.MIMEBase import MIMEBase
from email.MIMEText import MIMEText
from email.Utils import COMMASPACE, formatdate
from email import Encoders
from email.header import Header

from tg import expose, redirect, validate, flash, config, response, request
from budget.model import *

DISPLAY_DATE_FORMAT = "%Y-%m-%d"

__all__ = ["gs", "filterAndSorted", "tabFocus", "Date2Text", "getOr404", "sendEmail", "advancedSendMail", "number2alphabet", "alphabet2number", "serveFile", "null2blank",
            "rpacEncrypt", "rpacDecrypt", "sysUpload", "OrderedDict", "makeException", "logError",
           "OrderedSet", "ReportGenerationException", "createToken", ]

gs = lambda kw, *ns : map(lambda n : kw.get(n, None), ns)

filterAndSorted = lambda  prefix, kw: sorted(filter(lambda (k, v): k.startswith(prefix), kw.iteritems()), cmp = lambda x, y:cmp(x[0], y[0]))

def tabFocus(tab_type = ""):
    def decorator(fun):
        def returnFun(*args, **keywordArgs):
            returnVal = fun(*args, **keywordArgs)
            if type(returnVal) == dict and "tab_focus" not in returnVal:
                returnVal["tab_focus"] = tab_type
            return returnVal
        return returnFun
    return decorator

def Date2Text(value = None, dateTimeFormat = DISPLAY_DATE_FORMAT, defaultNow = False):
    if not value and defaultNow : value = dt.now()

    format = dateTimeFormat
    result = value

    if isinstance(value, date):
        try:
            result = value.strftime(format)
        except:
            traceback.print_exc()
    elif hasattr(value, "strftime"):
        try:
            result = value.strftime(format)
        except:
            traceback.print_exc()

    if not result:
        result = ""

    return result

def getOr404(obj, id, redirect_url = "/index", message = "The record deosn't exist!"):
    try:
        v = DBSession.query(obj).get(id)
        if v : return v
#        else : raise "No such obj"
        else : raise makeException("No such obj!")
    except:
        traceback.print_exc()
        flash(message)
        redirect(redirect_url)

# This method is used in MS Excel to convert the header column from number to alphalbet
# def number2alphabet(n):
#    result = []
#    while n >= 0:
#        if n > 26:
#            result.insert(0, n % 26)
#            n /= 26
#        else:
#            result.insert(0, n)
#            break
#    return "".join([chr(r + 64) for r in result ]) if result else None

def number2alphabet(n):
    result = []
    while n > 0 :
        x , y = n / 26, n % 26
        result.append(y)
        if x > 0 :
            n = x
        else:
            break

    p = 0
    for i in range(len(result)):
        result[i] += p
        if result[i] <= 0 and i + 1 < len(result):
            result[i] += 26
            p = -1
        else:
            p = 0

    if result[-1] <= 0 : result = result[:-1]
    result.reverse()
    return "".join(map(lambda v:chr(v + 64), result))

def alphabet2number(str):
    if not str or not isinstance(str, basestring) : raise TypeError
    if not str.isalpha() : raise ValueError
    return  reduce(lambda a, b:  (a * 26) + ord(b) - ord("a") + 1, str.lower(), 0)

def sendEmail(send_from, send_to, subject, text, cc_to = [], files = [], server = "192.168.42.14"):
    assert type(send_to) == list
    assert type(files) == list

    msg = MIMEMultipart()
    msg.set_charset("utf-8")
    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)

    if cc_to:
        assert type(cc_to) == list
        msg['cc'] = COMMASPACE.join(cc_to)
        send_to.extend(cc_to)

    msg['Date'] = formatdate(localtime = True)
    msg['Subject'] = subject.replace("\n", ' ')

    msg.attach(MIMEText(text))

    for f in files:
        part = MIMEBase('application', "octet-stream")
        if isinstance(f, basestring):
            part.set_payload(open(f, "rb").read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % Header(os.path.basename(f), 'utf-8'))
        elif hasattr(f, "file_path") and hasattr(f, "file_name"):
            part.set_payload(open(f.file_path, "rb").read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % Header(f.file_name, 'utf-8'))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

def advancedSendMail(send_from, send_to, subject, text, html, cc_to = [], files = [], server = "192.168.42.14"):
    assert type(send_to) == list
    assert type(files) == list

    if not text and not html:
        raise "No content to send!"
    elif text and not html :
        msg = MIMEText(text, "plain", _charset = 'utf-8')  # fix the default encoding problem
    elif not text and html:
        msg = MIMEText(html, "html", _charset = 'utf-8')  # fix the default encoding problem
    else:
        msg = MIMEMultipart("alternative")
        msg.attach(MIMEText(text, "plain", _charset = 'utf-8'))
        msg.attach(MIMEText(html, "html", _charset = 'utf-8'))

    msg.set_charset("utf-8")
    if len(files) > 0 :
        tmpmsg = msg
        msg = MIMEMultipart()
        msg.attach(tmpmsg)

    msg['From'] = send_from
    msg['To'] = COMMASPACE.join(send_to)

    if cc_to:
        assert type(cc_to) == list
        msg['cc'] = COMMASPACE.join(cc_to)
        send_to.extend(cc_to)

    msg['Date'] = formatdate(localtime = True)
    msg['Subject'] = subject

    for f in files:
        part = MIMEBase('application', "octet-stream")
        if isinstance(f, basestring):
            part.set_payload(open(f, "rb").read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % Header(os.path.basename(f), 'utf-8'))
        elif hasattr(f, "file_path") and hasattr(f, "file_name"):
            part.set_payload(open(f.file_path, "rb").read())
            Encoders.encode_base64(part)
            part.add_header('Content-Disposition', 'attachment; filename="%s"' % Header(f.file_name, 'utf-8'))
        msg.attach(part)

    smtp = smtplib.SMTP(server)
    smtp.sendmail(send_from, send_to, msg.as_string())
    smtp.close()

def serveFile(filePath, fileName = None, contentType = "application/x-download", contentDisposition = "attachment"):
    response.headers['Content-type'] = 'application/x-download' if not contentType else contentType

    isIE = request.headers["User-Agent"].find("MSIE") > -1
    if not fileName:
        response.headers['Content-Disposition'] = "%s;filename=%s" % (contentDisposition, os.path.basename(filePath))
    else:
        if isIE :
            response.headers['Content-Disposition'] = "%s;filename=%s" % (contentDisposition, urllib.quote(fileName.encode('utf-8')))
        else:
            f = "=?utf-8?B?%s?=" % base64.b64encode(fileName)
            response.headers['Content-Disposition'] = "%s;filename=%s" % (contentDisposition, f)

    response.headers['Pragma'] = 'public'  # for IE
    response.headers['Cache-control'] = 'max-age=0'  # for IE
    f = open(filePath, 'rb')
    content = "".join(f.readlines())
    f.close()
    return content

def defaultIfNone(blackList = [None, ], default = ""):
    def returnFun(value):
        defaultValue = default() if callable(default) else default
        if value in blackList:
            return defaultValue
        else:
            try:
                return str(value)
            except:
                try:
                    return repr(value)
                except:
                    pass
        return defaultValue
    return returnFun

null2blank = defaultIfNone(blackList = [None, "NULL", "null", "None"])

def rpacEncrypt(v):
    c = base64.b64encode(unicode(v))
    e = hashlib.md5()
    e.update("r-pac%sorsay" % unicode(v))
    k = e.hexdigest()[5:15]
#    k = sha.new("r-pac%sorsay" % unicode(v)).hexdigest()[5:15]
    return c + k

def rpacDecrypt(enStr):
    if not enStr or len(enStr) < 10 : return (False, None)
    k = enStr[-10:]
    c = base64.b64decode(enStr[:-10])

    e = hashlib.md5()
    e.update("r-pac%sorsay" % unicode(c))
    kk = e.hexdigest()[5:15]

    if k != kk : return (False, None)
#    if sha.new("r-pac%sorsay" % c).hexdigest()[5:15] != k : return (False,None)
    return (True, c)

def sysUpload(attachment_list, attachment_name_list = None, folder = "sys", return_obj = False):

#    if not (attachment_list and attachment_name_list) : return (1,[])
    if type(attachment_list) != list : attachment_list = [attachment_list]
    if not attachment_name_list: attachment_name_list = [getattr(i, 'filename', None) for i in attachment_list]
    if type(attachment_name_list) != list : attachment_name_list = [attachment_name_list]
    if len(attachment_list) != len(attachment_name_list) : return (2, [])

    def _todo(a, n):
        try:
            file_path = a.filename
            (pre, ext) = os.path.splitext(file_path)
            path_prefix = os.path.join(config.download_dir, folder)
            if not os.path.exists(path_prefix) : os.makedirs(path_prefix)

            file_name = "%s%.4d%s" % (dt.now().strftime("%Y%m%d%H%M%S"), random.randint(1, 1000), ext)
            full_path = os.path.join(path_prefix, file_name)

            f = open(full_path, "wb")
            f.write(a.file.read())
            f.close()

            db_file_name = n or file_name
            if db_file_name.find(".") < 0 : db_file_name = db_file_name + ext

            obj = UploadObject(file_name = db_file_name, file_path = os.path.join(folder, file_name))
            DBSession.add(obj)
            DBSession.flush()
            return obj.id if not return_obj else obj
#            return obj.id
        except:
            traceback.print_exc()
            logError()
            return None

    return (0, [_todo(a, n) for a, n in zip(attachment_list, attachment_name_list) if hasattr(a, "filename")])

def makeException(msg):
    class _ExceptionClz(Exception):
        def __init__(self, msg = msg):
            self.msg = msg
            self.is_customize = True

        def __str__(self): return self.msg
        def __unicode__(self): return self.msg
        def __repr__(self): return self.msg

    return _ExceptionClz

def logError():
    try:
        content = cStringIO.StringIO()
        content.write("\n\n%s  %s %s\n" % ("*" * 10, dt.now(), request.identity["user"]))
        traceback.print_exc(file = content)
        if not os.path.exists(config.log_dir):
            os.makedirs(config.log_dir)
        f = file(os.path.join(config.log_dir, "error-%s.txt" % Date2Text(defaultNow = True)), 'ab')
        f.write(content.getvalue())
        f.close()
        print traceback.format_exc().splitlines()[-1]
    except:
        pass

#===============================================================================
# Copy from Sqlalchemy by CL on 2010-06-11
#
#===============================================================================

class OrderedDict(dict):
    """A dict that returns keys/values/items in the order they were added."""

    def __init__(self, ____sequence = None, **kwargs):
        self._list = []
        if ____sequence is None:
            if kwargs:
                self.update(**kwargs)
        else:
            self.update(____sequence, **kwargs)

    def clear(self):
        self._list = []
        dict.clear(self)

    def copy(self):
        return self.__copy__()

    def __copy__(self):
        return OrderedDict(self)

    def sort(self, *arg, **kw):
        self._list.sort(*arg, **kw)

    def update(self, ____sequence = None, **kwargs):
        if ____sequence is not None:
            if hasattr(____sequence, 'keys'):
                for key in ____sequence.keys():
                    self.__setitem__(key, ____sequence[key])
            else:
                for key, value in ____sequence:
                    self[key] = value
        if kwargs:
            self.update(kwargs)

    def setdefault(self, key, value):
        if key not in self:
            self.__setitem__(key, value)
            return value
        else:
            return self.__getitem__(key)

    def __iter__(self):
        return iter(self._list)

    def values(self):
        return [self[key] for key in self._list]

    def itervalues(self):
        return iter(self.values())

    def keys(self):
        return list(self._list)

    def iterkeys(self):
        return iter(self.keys())

    def items(self):
        return [(key, self[key]) for key in self.keys()]

    def iteritems(self):
        return iter(self.items())

    def __setitem__(self, key, object):
        if key not in self:
            self._list.append(key)
        dict.__setitem__(self, key, object)

    def __delitem__(self, key):
        dict.__delitem__(self, key)
        self._list.remove(key)

    def pop(self, key, *default):
        present = key in self
        value = dict.pop(self, key, *default)
        if present:
            self._list.remove(key)
        return value

    def popitem(self):
        item = dict.popitem(self)
        self._list.remove(item[0])
        return item

class OrderedSet(set):
    def __init__(self, d = None):
        set.__init__(self)
        self._list = []
        if d is not None:
            self.update(d)

    def add(self, element):
        if element not in self:
            self._list.append(element)
        set.add(self, element)

    def remove(self, element):
        set.remove(self, element)
        self._list.remove(element)

    def insert(self, pos, element):
        if element not in self:
            self._list.insert(pos, element)
        set.add(self, element)

    def discard(self, element):
        if element in self:
            self._list.remove(element)
            set.remove(self, element)

    def clear(self):
        set.clear(self)
        self._list = []

    def __getitem__(self, key):
        return self._list[key]

    def __iter__(self):
        return iter(self._list)

    def __repr__(self):
        return '%s(%r)' % (self.__class__.__name__, self._list)

    __str__ = __repr__

    def update(self, iterable):
        add = self.add
        for i in iterable:
            add(i)
        return self

    __ior__ = update

    def union(self, other):
        result = self.__class__(self)
        result.update(other)
        return result

    __or__ = union

    def intersection(self, other):
        other = set(other)
        return self.__class__(a for a in self if a in other)

    __and__ = intersection

    def symmetric_difference(self, other):
        other = set(other)
        result = self.__class__(a for a in self if a not in other)
        result.update(a for a in other if a not in self)
        return result

    __xor__ = symmetric_difference

    def difference(self, other):
        other = set(other)
        return self.__class__(a for a in self if a not in other)

    __sub__ = difference

    def intersection_update(self, other):
        other = set(other)
        set.intersection_update(self, other)
        self._list = [ a for a in self._list if a in other]
        return self

    __iand__ = intersection_update

    def symmetric_difference_update(self, other):
        set.symmetric_difference_update(self, other)
        self._list = [ a for a in self._list if a in self]
        self._list += [ a for a in other._list if a in self]
        return self

    __ixor__ = symmetric_difference_update

    def difference_update(self, other):
        set.difference_update(self, other)
        self._list = [ a for a in self._list if a in self]
        return self

    __isub__ = difference_update

#===============================================================================
# exception define
#===============================================================================
class ReportGenerationException(Exception):
    def __init__(self, msg = "Error when generate the report!"):
        self.msg = msg

    def __str__(self):
        return self.msg

def createToken():
    token = request.identity["user"].user_name + dt.now().strftime("%y%m%d%H%M%S") + str(random.randint(100, 999))
    return sha.new(token).hexdigest()


text:
//
//  HHHorizontalPagingView.h
//  HHHorizontalPagingView
//
//  Created by Huanhoo on 15/7/16.
//  Copyright (c) 2015年 Huanhoo. All rights reserved.
//

#import <UIKit/UIKit.h>
#import "JYSegmentViewProtocol.h"

@class HHHorizontalPagingView;

// 使用 allowPullToRefresh 结束刷新需要发出通知
extern NSString* kHHHorizontalScrollViewRefreshStartNotification;
extern NSString* kHHHorizontalScrollViewRefreshEndNotification;
// 监听该通知收回刷新 在切换界面时如果刷新未结束会发出此通知
extern NSString* kHHHorizontalTakeBackRefreshEndNotification;

@protocol HHHorizontalPagingViewDelegate<NSObject>

// 下方左右滑UIScrollView设置
- (NSInteger)numberOfSectionsInPagingView:(HHHorizontalPagingView *)pagingView;
- (UIScrollView *)pagingView:(HHHorizontalPagingView *)pagingView viewAtIndex:(NSInteger)index;

//headerView 设置
- (CGFloat)headerHeightInPagingView:(HHHorizontalPagingView *)pagingView;
- (UIView *)headerViewInPagingView:(HHHorizontalPagingView *)pagingView;

#pragma mark - segmentView 配置
//segmentView 的固定高度 必须实现
- (CGFloat)segmentHeightInPagingView:(HHHorizontalPagingView *)pagingView;
@optional
// 如不实现 segmentViewHeight:pagingView: 则必须实现该代理 采用JYSegmentView
- (NSArray<UIButton*> *)segmentButtonsInPagingView:(HHHorizontalPagingView *)pagingView;
- (UIView<JYSegmentViewProtocol> *)segmentViewHeight:(CGFloat)height pagingView:(HHHorizontalPagingView *)pagingView;

@optional
// 非当前页点击segment
- (void)pagingView:(HHHorizontalPagingView*)pagingView segmentDidSelected:(UIView *)item atIndex:(NSInteger)selectedIndex;
// 当前页点击segment
- (void)pagingView:(HHHorizontalPagingView*)pagingView segmentDidSelectedSameItem:(UIView *)item atIndex:(NSInteger)selectedIndex;

// 视图切换完成时调用 从哪里切换到哪里
- (void)pagingView:(HHHorizontalPagingView*)pagingView didSwitchIndex:(NSInteger)aIndex to:(NSInteger)toIndex;

/*
  与 magnifyTopConstraint 属性相对应  下拉时如需要放大,则传入的图片的上边距约束
  考虑到开发中很少使用原生约束,故放开代理方法 用于用户自行根据 偏移处理相应效果

  该版本将 magnifyTopConstraint 属性删除
  该代理 和 监听 self.contentOffset 效果是一样的
 */
- (void)pagingView:(HHHorizontalPagingView*)pagingView scrollTopOffset:(CGFloat)offset;

@end

@interface HHHorizontalPagingView : UIView

/**
 *  segment据顶部的距离
 */
@property (nonatomic, assign) CGFloat segmentTopSpace;

/**
 *  是否使用手势模拟 默认 NO
 *  YES : 会在headerView上添加手势,模拟scorlView 的减速滚动等(效果接近系统)
 *  NO  :  拦截响应view实现,效果最好,但是headerView响应链断裂
 */
@property (nonatomic, assign) BOOL isGesturesSimulate;

/**
 *  允许下拉刷新 默认为NO
 *  pullOffset 下拉的偏移量
 *
 *  在 下拉刷新 开始 和 结束时 需要发出通知
 *  kHHHorizontalScrollViewRefreshStartNotification
 *  kHHHorizontalScrollViewRefreshEndNotification
 *
    object 传入刷新 的 ScrollView
    [[NSNotificationCenter defaultCenter] postNotificationName:kHHHorizontalScrollViewRefreshEndNotification object:weakSelf.tableView userInfo:nil];
 *
 * - (void)viewWillDisappear:(BOOL)animated 或 - (void)viewWillAppear:(BOOL)animated 也要收起刷新动画
 *
 */
@property (nonatomic, assign) BOOL allowPullToRefresh;
@property (nonatomic, assign, readonly) CGFloat pullOffset;

// 用于整体下拉刷新
@property (nonatomic, assign) CGPoint contentOffset;
@property (nonatomic, assign) BOOL isDragging;

/**
 *  缓存视图数 默认是 3
 */
@property (nonatomic, assign) CGFloat maxCacheCout;

/**
 *  切换视图
 */
@property (nonatomic, strong, readonly) UIView<JYSegmentViewProtocol> *segmentView;

/**
 *  实例化横向分页控件
 *  @return  控件对象
 */
- (instancetype)initWithFrame:(CGRect)frame delegate:(id<HHHorizontalPagingViewDelegate>) delegate;

/**
 *  手动控制滚动到某个视图
 *
 *  @param pageIndex 页号
 */
- (void)scrollToIndex:(NSInteger)pageIndex;

/**
 *  左右滑动
 *
 *  @param enable 是否允许滚动
 */
- (void)scrollEnable:(BOOL)enable;

/**
 *  获取当前的 UIScrollView
 *
 *  @param index 页号
 */
- (UIScrollView *)scrollViewAtIndex:(NSInteger)index;

// 进行页面刷新
- (void)reload;

@end

redpajama_set_name: RedPajamaGithub


text:
package org.molasdin.wbase.transaction.jdbc;

import java.sql.ResultSet;

/**
 * Created by dbersenev on 21.03.2016.
 */
public enum ResultSetConcurrency {
    READ_ONLY(ResultSet.CONCUR_READ_ONLY),
    UPDATABLE(ResultSet.CONCUR_UPDATABLE);

    private int value;

    private ResultSetConcurrency(int value) {
        this.value = value;
    }

    public int value(){
        return value;
    }
}


text:
var states = [];
var alphabet = "abc";

var paper_width = 900;
var paper_height = 500;

var graph = new joint.dia.Graph;

var paper = new joint.dia.Paper({
    el: $('#diagram'),
    width: paper_width,
    height: paper_height,
    gridSize: 1,
    model: graph
});

paper.on('blank:pointerclick', function(evt, x, y) {
	console.log("pulsaste ");
	// console.log(paper);
	states.push(state(getRandomInt(5, paper_width-40), getRandomInt(5, paper_height-40), "q0"));
	console.log(states);
});

function state(x, y, label) {

    var cell = new joint.shapes.fsa.State({
        position: { x: x, y: y },
        inPorts: ["a", "b"],
        size: { width: 60, height: 60 },
        attrs: { text : { text: label }}
    });
    graph.addCell(cell);
    return cell;
};

function link(source, target, label, vertices) {

    var cell = new joint.shapes.fsa.Arrow({
        source: { id: source.id },
        target: { id: target.id },
        labels: [{ position: .5, attrs: { text: { text: label || '', 'font-weight': 'bold' } } }],
        vertices: vertices || []
    });
    graph.addCell(cell);
    return cell;
}

function getRandomInt(min, max) {
  return Math.floor(Math.random() * (max - min)) + min;
}


text:
#include "test.h"

#include "memdebug.h"

static char data[] =
#ifdef CURL_DOES_CONVERSIONS
  /* ASCII representation with escape sequences for non-ASCII platforms */
  "\x74\x68\x69\x73\x20\x69\x73\x20\x77\x68\x61\x74\x20\x77\x65\x20\x70"
  "\x6f\x73\x74\x20\x74\x6f\x20\x74\x68\x65\x20\x73\x69\x6c\x6c\x79\x20"
  "\x77\x65\x62\x20\x73\x65\x72\x76\x65\x72";
#else
  "this is what we post to the silly web server";
#endif

static const char name[] = "fieldname";

/* This test attempts to use all form API features that are not
 * used elsewhere.
 */

/* curl_formget callback to count characters. */
static size_t count_chars(void *userp, const char *buf, size_t len)
{
  size_t *pcounter = (size_t *) userp;

  (void) buf;
  *pcounter += len;
  return len;
}

int test(char *URL)
{
  CURL *curl = NULL;
  CURLcode res = TEST_ERR_MAJOR_BAD;
  CURLFORMcode formrc;
  struct curl_slist *headers, *headers2 = NULL;
  struct curl_httppost *formpost = NULL;
  struct curl_httppost *lastptr = NULL;
  struct curl_forms formarray[3];
  size_t formlength = 0;
  char flbuf[32];
  long contentlength = 0;

  if(curl_global_init(CURL_GLOBAL_ALL) != CURLE_OK) {
    fprintf(stderr, "curl_global_init() failed\n");
    return TEST_ERR_MAJOR_BAD;
  }

  /* Check proper name and data copying, as well as headers. */
  headers = curl_slist_append(NULL, "X-customheader-1: Header 1 data");
  if(!headers) {
    goto test_cleanup;
  }
  headers2 = curl_slist_append(headers, "X-customheader-2: Header 2 data");
  if(!headers2) {
    goto test_cleanup;
  }
  headers = headers2;
  headers2 = curl_slist_append(headers, "Content-Type: text/plain");
  if(!headers2) {
    goto test_cleanup;
  }
  headers = headers2;
  formrc = curl_formadd(&formpost, &lastptr,
                        CURLFORM_COPYNAME, &name,
                        CURLFORM_COPYCONTENTS, &data,
                        CURLFORM_CONTENTHEADER, headers,
                        CURLFORM_END);

  if(formrc) {
    printf("curl_formadd(1) = %d\n", (int) formrc);
    goto test_cleanup;
  }

  contentlength = (long)(strlen(data) - 1);

  /* Use a form array for the non-copy test. */
  formarray[0].option = CURLFORM_PTRCONTENTS;
  formarray[0].value = data;
  formarray[1].option = CURLFORM_CONTENTSLENGTH;
  formarray[1].value = (char *)(size_t)contentlength;
  formarray[2].option = CURLFORM_END;
  formarray[2].value = NULL;
  formrc = curl_formadd(&formpost,
                        &lastptr,
                        CURLFORM_PTRNAME, name,
                        CURLFORM_NAMELENGTH, strlen(name) - 1,
                        CURLFORM_ARRAY, formarray,
                        CURLFORM_FILENAME, "remotefile.txt",
                        CURLFORM_END);

  if(formrc) {
    printf("curl_formadd(2) = %d\n", (int) formrc);
    goto test_cleanup;
  }

  /* Now change in-memory data to affect CURLOPT_PTRCONTENTS value.
     Copied values (first field) must not be affected.
     CURLOPT_PTRNAME actually copies the name thus we do not test this here. */
  data[0]++;

  /* Check multi-files and content type propagation. */
  formrc = curl_formadd(&formpost,
                        &lastptr,
                        CURLFORM_COPYNAME, "multifile",
                        CURLFORM_FILE, libtest_arg2,    /* Set in first.c. */
                        CURLFORM_FILE, libtest_arg2,
                        CURLFORM_CONTENTTYPE, "text/whatever",
                        CURLFORM_FILE, libtest_arg2,
                        CURLFORM_END);

  if(formrc) {
    printf("curl_formadd(3) = %d\n", (int) formrc);
    goto test_cleanup;
  }

  /* Check data from file content. */
  formrc = curl_formadd(&formpost,
                        &lastptr,
                        CURLFORM_COPYNAME, "filecontents",
                        CURLFORM_FILECONTENT, libtest_arg2,
                        CURLFORM_END);

  if(formrc) {
    printf("curl_formadd(4) = %d\n", (int) formrc);
    goto test_cleanup;
  }

  /* Measure the current form length.
   * This is done before including stdin data because we want to reuse it
   * and stdin cannot be rewound.
   */
  curl_formget(formpost, (void *) &formlength, count_chars);

  /* Include length in data for external check. */
  curl_msnprintf(flbuf, sizeof(flbuf), "%lu", (unsigned long) formlength);
  formrc = curl_formadd(&formpost,
                        &lastptr,
                        CURLFORM_COPYNAME, "formlength",
                        CURLFORM_COPYCONTENTS, &flbuf,
                        CURLFORM_END);
  if(formrc) {
    printf("curl_formadd(5) = %d\n", (int) formrc);
    goto test_cleanup;
  }

  /* Check stdin (may be problematic on some platforms). */
  formrc = curl_formadd(&formpost,
                        &lastptr,
                        CURLFORM_COPYNAME, "standardinput",
                        CURLFORM_FILE, "-",
                        CURLFORM_END);
  if(formrc) {
    printf("curl_formadd(6) = %d\n", (int) formrc);
    goto test_cleanup;
  }

  curl = curl_easy_init();
  if(!curl) {
    fprintf(stderr, "curl_easy_init() failed\n");
    goto test_cleanup;
  }

  /* First set the URL that is about to receive our POST. */
  test_setopt(curl, CURLOPT_URL, URL);

  /* send a multi-part formpost */
  test_setopt(curl, CURLOPT_HTTPPOST, formpost);

  /* get verbose debug output please */
  test_setopt(curl, CURLOPT_VERBOSE, 1L);

  /* include headers in the output */
  test_setopt(curl, CURLOPT_HEADER, 1L);

  /* Perform the request, res will get the return code */
  res = curl_easy_perform(curl);

test_cleanup:

  /* always cleanup */
  curl_easy_cleanup(curl);

  /* now cleanup the formpost chain */
  curl_formfree(formpost);
  curl_slist_free_all(headers);

  curl_global_cleanup();

  return res;
}


text:
#region BSD License

#endregion

namespace IntegrationPackage
{
    using Clide.Commands;

    [CommandFilter(Constants.PackageGuid, "{5efc7975-14bc-11cf-9b2b-00aa00573819}", 99999999)]
    public class BadCommandFilter : ICommandFilter
    {
        public static bool QueryStatusCalled;

        public void QueryStatus(IMenuCommand command)
        {
            QueryStatusCalled = true;
        }
    }
}


text:
(function () {

    var defaultMatrix = SceneJS_math_lookAtMat4c(0, 0, 10, 0, 0, 0, 0, 1, 0);
    var defaultMat = new Float32Array(defaultMatrix);
    var normalMat = SceneJS_math_transposeMat4(SceneJS_math_inverseMat4(defaultMat, SceneJS_math_mat4()));
    var defaultNormalMat = new Float32Array(normalMat);

    /**
     * The default state core singleton for {@link SceneJS.Lookat} nodes
     */
    var defaultCore = {
        type:"lookAt",
        stateId:SceneJS._baseStateId++,
        matrix:defaultMatrix,
        mat:defaultMat,
        normalMatrix:normalMat,
        normalMat:defaultNormalMat,
        lookAt:SceneJS_math_LOOKAT_ARRAYS
    };

    var coreStack = [];
    var stackLen = 0;

    SceneJS_events.addListener(
        SceneJS_events.SCENE_COMPILING,
        function (params) {
            params.engine.display.viewTransform = defaultCore;
            stackLen = 0;
        });

    /**
     * @class Scene graph node which defines the viewing transform for the {@link SceneJS.Geometry}s within its subgraph
     * @extends SceneJS.Node
     */
    SceneJS.Lookat = SceneJS_NodeFactory.createNodeType("lookAt");

    SceneJS.Lookat.prototype._init = function (params) {

        this._mat = null;

        this._xf = {
            type:"lookat"
        };

        if (this._core.useCount == 1) { // This node is the resource definer

            this._core.eyeX = 0;
            this._core.eyeY = 0;
            this._core.eyeZ = 10.0;

            this._core.lookX = 0;
            this._core.lookY = 0;
            this._core.lookZ = 0;

            this._core.upX = 0;
            this._core.upY = 1;
            this._core.upZ = 0;

            if (!params.eye && !params.look && !params.up) {
                this.setEye({x:0, y:0, z:10.0 });
                this.setLook({x:0, y:0, z:0 });
                this.setUp({x:0, y:1.0, z:0 });
            } else {
                this.setEye(params.eye);
                this.setLook(params.look);
                this.setUp(params.up);
            }

            var core = this._core;

            var self = this;

            this._core.rebuild = function () {

                core.matrix = SceneJS_math_lookAtMat4c(
                    core.eyeX, core.eyeY, core.eyeZ,
                    core.lookX, core.lookY, core.lookZ,
                    core.upX, core.upY, core.upZ);

                core.lookAt = {
                    eye:[core.eyeX, core.eyeY, core.eyeZ ],
                    look:[core.lookX, core.lookY, core.lookZ ],
                    up:[core.upX, core.upY, core.upZ ]
                };

                if (!core.mat) { // Lazy-create arrays
                    core.mat = new Float32Array(core.matrix);
                    core.normalMat = new Float32Array(
                        SceneJS_math_transposeMat4(SceneJS_math_inverseMat4(core.matrix, SceneJS_math_mat4())));

                } else { // Insert into arrays
                    core.mat.set(core.matrix);
                    core.normalMat.set(SceneJS_math_transposeMat4(SceneJS_math_inverseMat4(core.matrix, SceneJS_math_mat4())));
                }

                self.publish("matrix", core.matrix);

                core.dirty = false;
            };

            this._core.dirty = true;

            // Rebuild on every scene tick
            // https://github.com/xeolabs/scenejs/issues/277
            this._tick = this.getScene().on("tick", function () {
                if (self._core.dirty) {
                    self._core.rebuild();
                }
            });
        }
    };

    /**
     * Returns the default view transformation matrix
     * @return {Float32Array}
     */
    SceneJS.Lookat.getDefaultMatrix = function () {
        return defaultMat;
    };

    SceneJS.Lookat.prototype.setEye = function (eye) {

        eye = eye || {};

        if (eye.x != undefined && eye.x != null) {
            this._core.eyeX = eye.x;
        }

        if (eye.y != undefined && eye.y != null) {
            this._core.eyeY = eye.y;
        }

        if (eye.z != undefined && eye.z != null) {
            this._core.eyeZ = eye.z;
        }

        this._core.dirty = true;
        this._engine.display.imageDirty = true;

        return this;
    };

    SceneJS.Lookat.prototype.incEye = function (eye) {
        eye = eye || {};
        this._core.eyeX += (eye.x != undefined && eye.x != null) ? eye.x : 0;
        this._core.eyeY += (eye.y != undefined && eye.y != null) ? eye.y : 0;
        this._core.eyeZ += (eye.z != undefined && eye.z != null) ? eye.z : 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.setEyeX = function (x) {
        this._core.eyeX = x || 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.setEyeY = function (y) {
        this._core.eyeY = y || 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.setEyeZ = function (z) {
        this._core.eyeZ = z || 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incEyeX = function (x) {
        this._core.eyeX += x;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incEyeY = function (y) {
        this._core.eyeY += y;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incEyeZ = function (z) {
        this._core.eyeZ += z;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.getEye = function () {
        return {
            x:this._core.eyeX,
            y:this._core.eyeY,
            z:this._core.eyeZ
        };
    };

    SceneJS.Lookat.prototype.setLook = function (look) {
        look = look || {};

        if (look.x != undefined && look.x != null) {
            this._core.lookX = look.x;
        }

        if (look.y != undefined && look.y != null) {
            this._core.lookY = look.y;
        }

        if (look.z != undefined && look.z != null) {
            this._core.lookZ = look.z;
        }

        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incLook = function (look) {
        look = look || {};
        this._core.lookX += (look.x != undefined && look.x != null) ? look.x : 0;
        this._core.lookY += (look.y != undefined && look.y != null) ? look.y : 0;
        this._core.lookZ += (look.z != undefined && look.z != null) ? look.z : 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.setLookX = function (x) {
        this._core.lookX = x || 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.setLookY = function (y) {
        this._core.lookY = y || 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.setLookZ = function (z) {
        this._core.lookZ = z || 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incLookX = function (x) {
        this._core.lookX += x;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incLookY = function (y) {
        this._core.lookY += y;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incLookZ = function (z) {
        this._core.lookZ += z;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.getLook = function () {
        return {
            x:this._core.lookX,
            y:this._core.lookY,
            z:this._core.lookZ
        };
    };

    SceneJS.Lookat.prototype.setUp = function (up) {
        up = up || {};

        if (up.x != undefined && up.x != null) {
            this._core.upX = up.x;
        }

        if (up.y != undefined && up.y != null) {
            this._core.upY = up.y;
        }

        if (up.z != undefined && up.z != null) {
            this._core.upZ = up.z;
        }

        this._core.dirty = true;
        this._engine.display.imageDirty = true;

        return this;
    };

    SceneJS.Lookat.prototype.incUp = function (up) {
        up = up || {};
        this._core.upX += (up.x != undefined && up.x != null) ? up.x : 0;
        this._core.upY += (up.y != undefined && up.y != null) ? up.y : 0;
        this._core.upZ += (up.z != undefined && up.z != null) ? up.z : 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.setUpX = function (x) {
        this._core.upX = x || 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.setUpY = function (y) {
        this._core.upY = y || 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.setUpZ = function (z) {
        this._core.upZ = z || 0;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incUpX = function (x) {
        this._core.upX += x;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incUpY = function (y) {
        this._core.upY += y;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.incUpZ = function (z) {
        this._core.upZ += z;
        this._core.dirty = true;
        this._engine.display.imageDirty = true;
        return this;
    };

    SceneJS.Lookat.prototype.getUp = function () {
        return {
            x:this._core.upX,
            y:this._core.upY,
            z:this._core.upZ
        };
    };

    /**
     * Returns a copy of the matrix as a 1D array of 16 elements
     * @returns {Number[16]}
     */
    SceneJS.Lookat.prototype.getMatrix = function () {

        if (this._core.dirty) {
            this._core.rebuild();
        }

        return  this._core.matrix.slice(0);
    };

    SceneJS.Lookat.prototype.getAttributes = function () {
        return {
            look:{
                x:this._core.lookX,
                y:this._core.lookY,
                z:this._core.lookZ
            },
            eye:{
                x:this._core.eyeX,
                y:this._core.eyeY,
                z:this._core.eyeZ
            },
            up:{
                x:this._core.upX,
                y:this._core.upY,
                z:this._core.upZ
            }
        };
    };

    SceneJS.Lookat.prototype._compile = function (ctx) {
        this._engine.display.viewTransform = coreStack[stackLen++] = this._core;
        this._compileNodes(ctx);
        this._engine.display.viewTransform = (--stackLen > 0) ? coreStack[stackLen - 1] : defaultCore;
        coreStack[stackLen] = null; // Release memory
    };

    SceneJS.Lookat.prototype._destroy = function () {
        // Stop publishing matrix on each tick
        this.getScene().off(this._tick);
    };

})();


text:
package com.planet_ink.coffee_mud.Abilities.Prayers;
import com.planet_ink.coffee_mud.core.interfaces.*;
import com.planet_ink.coffee_mud.core.*;
import com.planet_ink.coffee_mud.core.collections.*;
import com.planet_ink.coffee_mud.Abilities.interfaces.*;
import com.planet_ink.coffee_mud.Areas.interfaces.*;
import com.planet_ink.coffee_mud.Behaviors.interfaces.*;
import com.planet_ink.coffee_mud.CharClasses.interfaces.*;
import com.planet_ink.coffee_mud.Commands.interfaces.*;
import com.planet_ink.coffee_mud.Common.interfaces.*;
import com.planet_ink.coffee_mud.Exits.interfaces.*;
import com.planet_ink.coffee_mud.Items.interfaces.*;
import com.planet_ink.coffee_mud.Libraries.interfaces.*;
import com.planet_ink.coffee_mud.Locales.interfaces.*;
import com.planet_ink.coffee_mud.MOBS.interfaces.*;
import com.planet_ink.coffee_mud.Races.interfaces.*;

import java.util.*;

public class Prayer_RemovePoison extends Prayer implements MendingSkill
{
	@Override public String ID() { return "Prayer_RemovePoison"; }
	private final static String localizedName = CMLib.lang().L("Remove Poison");
	@Override public String name() { return localizedName; }
	@Override public int classificationCode(){return Ability.ACODE_PRAYER|Ability.DOMAIN_RESTORATION;}
	@Override public int abstractQuality(){ return Ability.QUALITY_OK_OTHERS;}
	@Override public long flags(){return Ability.FLAG_HOLY;}

	@Override
	public boolean supportsMending(Physical item)
	{
		if(!(item instanceof MOB))
			return false;
		final boolean canMend=returnOffensiveAffects(item).size()>0;
		return canMend;
	}

	public static List<Ability> returnOffensiveAffects(Physical fromMe)
	{
		final Vector<Ability> offenders=new Vector<Ability>();

		for(int a=0;a<fromMe.numEffects();a++) // personal
		{
			final Ability A=fromMe.fetchEffect(a);
			if((A!=null)&&((A.classificationCode()&Ability.ALL_ACODES)==Ability.ACODE_POISON))
				offenders.addElement(A);
		}
		return offenders;
	}

	@Override
	public int castingQuality(MOB mob, Physical target)
	{
		if(mob!=null)
		{
			if(target instanceof MOB)
			{
				if(supportsMending(target))
					return super.castingQuality(mob, target,Ability.QUALITY_BENEFICIAL_OTHERS);
			}
		}
		return super.castingQuality(mob,target);
	}

	@Override
	public boolean invoke(MOB mob, List<String> commands, Physical givenTarget, boolean auto, int asLevel)
	{
		final Physical target=getAnyTarget(mob,commands,givenTarget,Wearable.FILTER_UNWORNONLY);
		if(target==null)
			return false;

		if(!super.invoke(mob,commands,givenTarget,auto,asLevel))
			return false;

		final boolean success=proficiencyCheck(mob,0,auto);
		final List<Ability> offensiveAffects=returnOffensiveAffects(target);

		if((success)&&(offensiveAffects.size()>0))
		{
			final CMMsg msg=CMClass.getMsg(mob,target,this,verbalCastCode(mob,target,auto),auto?L("<T-NAME> feel(s) purified of <T-HIS-HER> poisons."):L("^S<S-NAME> @x1 that <T-NAME> be purified of <T-HIS-HER> poisons.^?",prayWord(mob)));
			if(mob.location().okMessage(mob,msg))
			{
				mob.location().send(mob,msg);
				for(int a=offensiveAffects.size()-1;a>=0;a--)
					offensiveAffects.get(a).unInvoke();
				if((target instanceof Drink)&&(((Drink)target).liquidType()==RawMaterial.RESOURCE_POISON))
				{
					((Drink)target).setLiquidType(RawMaterial.RESOURCE_FRESHWATER);
					target.basePhyStats().setAbility(0);
				}
				if(!CMLib.flags().isStillAffectedBy(target,offensiveAffects,false))
				{
					if(target instanceof MOB)
					{
						((MOB)target).tell(L("You feel much better!"));
						((MOB)target).recoverCharStats();
						((MOB)target).recoverMaxState();
					}
				}
				target.recoverPhyStats();
			}
		}
		else
		if(!auto)
			beneficialWordsFizzle(mob,target,auto?"":L("<S-NAME> @x1 that <T-NAME> be purified of <T-HIS-HER> poisons, but there is no answer.",prayWord(mob)));

		// return whether it worked
		return success;
	}
}


text:
<html>
<body>
	<img src="images/wireframe-week2-solochallenge.jpg">
</body>
</html>


text:
<?php

namespace App\Http\Controllers\Backend;

use App\Appointment;
use App\Events\CancelAppointment;
use App\Events\ChangeAppointmentAddress;
use App\Events\ChangeAppointmentDateTime;
use App\Seminar;
use App\Employee;
use App\Address;
use App\Booking;
use Barryvdh\DomPDF\Facade as PDF;
use Carbon\Carbon;
use App\Http\Requests;
use Cornford\Googlmapper\Facades\MapperFacade as Mapper;
use Illuminate\Support\Facades\Auth;

class AppointmentsController extends Controller
{
    protected $appointments;

    public function __construct(Appointment $appointments)
    {
        $this->appointments = $appointments;

        parent::__construct();
    }

    public function index()
    {
        if (Auth::guard('employee')->user()->isAdmin()) {
            $seminarappointments = Appointment::with('employee')->orderBy('created_at', 'desc')->paginate(10);
        } else {
            $seminarappointments = Appointment::with('employee')->where('employee_id', '=', Auth::guard('employee')->id())->orderBy('created_at', 'desc')->paginate(10);
        }

        return view('backend.seminarappointments.index', compact('seminarappointments'));
    }

    public function create(Appointment $seminarappointment)
    {
        $seminars = ['' => ''] + Seminar::all()->pluck('title', 'id')->toArray();

        $emp = Employee::select('id', 'lastname', 'firstname')->get();
        $employees = ['' => ''];
        foreach ($emp as $employee) {
            $employees[$employee->id] = $employee->lastname . ', ' . $employee->firstname;
        }

        return view('backend.seminarappointments.form', compact('seminarappointment', 'seminars', 'employees'));
    }

    public function store(Requests\Backend\StoreAppointmentRequest $request)
    {
        $address = Address::where('zip', '=', $request->zip)->where('city', '=', $request->city)->where('street', '=', $request->street)->where('housenumber', '=', $request->housenumber)->first();

        if (!$address) {
            $geo = Mapper::location('Germany' . $request->zip . $request->street . $request->housenumber);
            if ($geo) {
                $newaddress = Address::create(array(
                    'zip' => $request->zip,
                    'city' => $request->city,
                    'street' => $request->street,
                    'housenumber' => $request->housenumber,
                    'latitude' => $geo->getLatitude(),
                    'longitude' => $geo->getLongitude()
                ));
                $address = $newaddress;
            } else {
                return redirect()->back()->withErrors(['error' => 'Address not found.']);
            }
        }

        Appointment::create(array(
            'date' => $request->date,
            'time' => $request->time,
            'employee_id' => $request->employee_id,
            'seminar_id' => $request->seminar_id,
            'address_id' => $address->id
        ));

        return redirect(route('seminarappointments.index'))->with('status', 'Appointment has been created.');
    }

    public function edit($id)
    {
        $seminarappointment = Appointment::findOrFail($id);

        $seminars = ['' => ''] + Seminar::all()->pluck('title', 'id')->toArray();

        $emp = Employee::select('id', 'lastname', 'firstname')->get();
        $employees = ['' => ''];
        foreach ($emp as $employee) {
            $employees[$employee->id] = $employee->lastname . ', ' . $employee->firstname;
        }

        return view('backend.seminarappointments.form', compact('seminarappointment', 'seminars', 'employees'));
    }

    public function update(Requests\Backend\UpdateAppointmentRequest $request, $id)
    {
        $address = Address::where('zip', '=', $request->zip)->where('city', '=', $request->city)->where('street', '=', $request->street)->where('housenumber', '=', $request->housenumber)->first();

        if (!$address) {
            $geo = Mapper::location('Germany' . $request->zip . $request->street . $request->housenumber);
            if ($geo) {
                $newaddress = Address::create(array(
                    'zip' => $request->zip,
                    'city' => $request->city,
                    'street' => $request->street,
                    'housenumber' => $request->housenumber,
                    'latitude' => $geo->getLatitude(),
                    'longitude' => $geo->getLongitude()
                ));
                $address = $newaddress;
            } else {
                return redirect()->back()->withErrors(['error' => 'Address not found.']);
            }
        }

        $seminarappointment = Appointment::findOrFail($id);

        $olddate = $seminarappointment->date;
        $oldtime = Carbon::parse($seminarappointment->time)->format('H:i');
        $oldaddress_id = $seminarappointment->address_id;

        $seminarappointment->fill(array(
            'date' => $request->date,
            'time' => $request->time,
            'employee_id' => $request->employee_id,
            'seminar_id' => $request->seminar_id,
            'address_id' => $address->id
        ))->save();

        if ($olddate != $seminarappointment->date || $oldtime != $seminarappointment->time) {
            $participants = Booking::select('member_id')->where('appointment_id', '=', $seminarappointment->id)->get();
            foreach ($participants as $participant) {
                event(new ChangeAppointmentDateTime($participant->member, $olddate, $oldtime, $seminarappointment));
            }
        }
        if ($oldaddress_id != $seminarappointment->address_id) {
            $oldaddress = Address::findOrFail($oldaddress_id);
            $participants = Booking::select('member_id')->where('appointment_id', '=', $seminarappointment->id)->get();
            foreach ($participants as $participant) {
                event(new ChangeAppointmentAddress($participant->member, $oldaddress, $seminarappointment));
            }
        }

        return redirect(route('seminarappointments.index'))->with('status', 'Appointment has been updated.');
    }

    public function confirm($id)
    {
        $seminarappointment = Appointment::findOrFail($id);

        return view('backend.seminarappointments.confirm', compact('seminarappointment'));
    }

    public function destroy($id)
    {
        $seminarappointment = Appointment::findOrFail($id);
        $participants = Booking::select('member_id')->where('appointment_id', '=', $id)->get();
        foreach ($participants as $participant) {
            event(new CancelAppointment($participant->member, $seminarappointment));
        }

        Appointment::destroy($id);

        $this->deleteBookings($id);

        return redirect(route('seminarappointments.index'))->with('status', 'Appointment has been deleted.');
    }

    public function detail($id)
    {
        $seminarappointment = Appointment::with('employee', 'members')->findOrFail($id);

        return view('backend.seminarappointments.detail', compact('seminarappointment'));
    }

    public function deleteBookings($appointment_id)
    {
        $bookings = Booking::all()->where('appointment_id', '=', $appointment_id);

        foreach ($bookings as $booking) {
            Booking::destroy($booking->id);
        }
    }

    public function removeParticipant($appointment_id, $member_id)
    {
        $booking = Booking::where('appointment_id', '=', $appointment_id)->where('member_id', '=', $member_id)->first();

        Booking::destroy($booking->id);

        return redirect()->back()->with('status', 'Participant has been removed.');
    }

    public function participantPaid($appointment_id, $member_id)
    {
        $booking = Booking::where('appointment_id', '=', $appointment_id)->where('member_id', '=', $member_id)->first();

        $booking->fill(array(
            'paid' => true
        ))->save();

        return redirect()->back()->with('status', 'Marked as paid.');
    }

    public function createList($id)
    {
        $seminarappointment = Appointment::with('members', 'employee')->findOrFail($id);

        return PDF::loadView('backend.seminarappointments.list', ['seminarappointment' => $seminarappointment])->download($seminarappointment->seminar->title . '_' . date_format($seminarappointment->date, 'd.m.Y') . '.pdf');
    }
}


text:
<?php namespace Mmanos\Billing\Gateways\Local\Models;

use Illuminate\Database\Eloquent\Model;
use Illuminate\Database\Eloquent\SoftDeletes;

class Coupon extends Model
{
	use SoftDeletes;
	protected $connection = 'billinglocal';
	protected $guarded = array('id');
}


text:
package com.envone.dgi;

import com.envone.dgi.builder.Builder;
import com.envone.dgi.signer.Signer;
import com.envone.dgi.ws.DGIClient;

public class DGI {

  public static void main(String[] args) throws Exception {
    String jsonFile = args[0];
    String xmlFile = DGIUtil.changeExtension(jsonFile, "xml");
    String signedFile =  DGIUtil.appendFileName(xmlFile, "_signed");

    // build file
    Builder.buildDocument(jsonFile, xmlFile);

    // sign file
    Signer.signFile(xmlFile, signedFile);

    // send file
    DGIClient.sendEnvelope(signedFile);
  }

}


text:
namespace media {
namespace testing {

// This is a mock for the Chromium media::ProvisionFetcher (and not Fuchsia's
// similarly named ProvisioningFetcher protocol).
class MockProvisionFetcher : public ProvisionFetcher {
 public:
  MockProvisionFetcher();
  ~MockProvisionFetcher();

  // Disallow copy and assign
  MockProvisionFetcher(const MockProvisionFetcher&) = delete;
  MockProvisionFetcher(MockProvisionFetcher&&) = delete;
  MockProvisionFetcher& operator=(const MockProvisionFetcher&) = delete;
  MockProvisionFetcher& operator=(MockProvisionFetcher&&) = delete;

  MOCK_METHOD(void,
              Retrieve,
              (const GURL& default_url,
               const std::string& request_data,
               ResponseCB response_cb),
              (override));
};

}  // namespace testing
}  // namespace media

#endif  // MEDIA_FUCHSIA_CDM_SERVICE_MOCK_PROVISION_FETCHER_H_


text:
class EventsRegistration < ActiveRecord::Base
  belongs_to :registration
  belongs_to :event
end


text:
package watch

import (
	"testing"

	"k8s.io/kubernetes/pkg/runtime/schema"
)

type testType string

func (obj testType) GetObjectKind() schema.ObjectKind { return schema.EmptyObjectKind }

func TestFake(t *testing.T) {
	f := NewFake()

	table := []struct {
		t EventType
		s testType
	}{
		{Added, testType("foo")},
		{Modified, testType("qux")},
		{Modified, testType("bar")},
		{Deleted, testType("bar")},
		{Error, testType("error: blah")},
	}

	// Prove that f implements Interface by phrasing this as a function.
	consumer := func(w Interface) {
		for _, expect := range table {
			got, ok := <-w.ResultChan()
			if !ok {
				t.Fatalf("closed early")
			}
			if e, a := expect.t, got.Type; e != a {
				t.Fatalf("Expected %v, got %v", e, a)
			}
			if a, ok := got.Object.(testType); !ok || a != expect.s {
				t.Fatalf("Expected %v, got %v", expect.s, a)
			}
		}
		_, stillOpen := <-w.ResultChan()
		if stillOpen {
			t.Fatal("Never stopped")
		}
	}

	sender := func() {
		f.Add(testType("foo"))
		f.Action(Modified, testType("qux"))
		f.Modify(testType("bar"))
		f.Delete(testType("bar"))
		f.Error(testType("error: blah"))
		f.Stop()
	}

	go sender()
	consumer(f)
}

func TestRaceFreeFake(t *testing.T) {
	f := NewRaceFreeFake()

	table := []struct {
		t EventType
		s testType
	}{
		{Added, testType("foo")},
		{Modified, testType("qux")},
		{Modified, testType("bar")},
		{Deleted, testType("bar")},
		{Error, testType("error: blah")},
	}

	// Prove that f implements Interface by phrasing this as a function.
	consumer := func(w Interface) {
		for _, expect := range table {
			got, ok := <-w.ResultChan()
			if !ok {
				t.Fatalf("closed early")
			}
			if e, a := expect.t, got.Type; e != a {
				t.Fatalf("Expected %v, got %v", e, a)
			}
			if a, ok := got.Object.(testType); !ok || a != expect.s {
				t.Fatalf("Expected %v, got %v", expect.s, a)
			}
		}
		_, stillOpen := <-w.ResultChan()
		if stillOpen {
			t.Fatal("Never stopped")
		}
	}

	sender := func() {
		f.Add(testType("foo"))
		f.Action(Modified, testType("qux"))
		f.Modify(testType("bar"))
		f.Delete(testType("bar"))
		f.Error(testType("error: blah"))
		f.Stop()
	}

	go sender()
	consumer(f)
}

func TestEmpty(t *testing.T) {
	w := NewEmptyWatch()
	_, ok := <-w.ResultChan()
	if ok {
		t.Errorf("unexpected result channel result")
	}
	w.Stop()
	_, ok = <-w.ResultChan()
	if ok {
		t.Errorf("unexpected result channel result")
	}
}


text:
set -x

cd bazel_pip
virtualenv --system-site-packages --python=python .env
source .env/bin/activate
pip --version
pip install portpicker
pip install *.whl

# Use default configuration
yes "" | python configure.py

PIP_TEST_ROOT=pip_test_root
mkdir -p ${PIP_TEST_ROOT}
ln -s $(pwd)/tensorflow ${PIP_TEST_ROOT}/tensorflow
bazel test --define=no_tensorflow_py_deps=true \
      --test_lang_filters=py \
      --build_tests_only \
      -k \
      --test_tag_filters=-no_oss,-oss_serial,-no_pip,-nopip \
      --test_size_filters=small,medium \
      --test_timeout 300,450,1200,3600 \
      --test_output=errors \
      -- //${PIP_TEST_ROOT}/tensorflow/python/... \
      -//${PIP_TEST_ROOT}/tensorflow/python:virtual_gpu_test \
      -//${PIP_TEST_ROOT}/tensorflow/python:virtual_gpu_test_gpu \
      -//${PIP_TEST_ROOT}/tensorflow/python:collective_ops_gpu_test \
      -//${PIP_TEST_ROOT}/tensorflow/python:collective_ops_gpu_test_gpu


text:
package org.grycap.vmrc.exceptions;

public class DaoException extends Exception {
	private static final long serialVersionUID = 1L;

	public DaoException (String msg){
		super(msg);
	}
	public DaoException(Exception e) {
		super(e);
	}

	public DaoException(String msg, Exception e){
		super(msg,e);
	}
}


text:
use crate::generic_public_key_bytes::GenericPublicKeyBytes;
use crate::Error;
use eth2_serde_utils::hex::encode as hex_encode;
use serde::de::{Deserialize, Deserializer};
use serde::ser::{Serialize, Serializer};
use ssz::{Decode, Encode};
use std::fmt;
use std::hash::{Hash, Hasher};
use tree_hash::TreeHash;

/// The byte-length of a BLS public key when serialized in compressed form.
pub const PUBLIC_KEY_BYTES_LEN: usize = 48;

/// Represents the public key at infinity.
pub const INFINITY_PUBLIC_KEY: [u8; PUBLIC_KEY_BYTES_LEN] = [
    0xc0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
    0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0,
];

/// Implemented on some struct from a BLS library so it may be used as the `point` in a
/// `GenericPublicKey`.
pub trait TPublicKey: Sized + Clone {
    /// Serialize `self` as compressed bytes.
    fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN];

    /// Deserialize `self` from compressed bytes.
    fn deserialize(bytes: &[u8]) -> Result<Self, Error>;
}

/// A BLS public key that is generic across some BLS point (`Pub`).
///
/// Provides generic functionality whilst deferring all serious cryptographic operations to `Pub`.
#[derive(Clone)]
pub struct GenericPublicKey<Pub> {
    /// The underlying point which performs *actual* cryptographic operations.
    point: Pub,
}

impl<Pub> GenericPublicKey<Pub>
where
    Pub: TPublicKey,
{
    /// Instantiates `Self` from a `point`.
    pub(crate) fn from_point(point: Pub) -> Self {
        Self { point }
    }

    /// Returns a reference to the underlying BLS point.
    pub(crate) fn point(&self) -> &Pub {
        &self.point
    }

    /// Returns `self.serialize()` as a `0x`-prefixed hex string.
    pub fn as_hex_string(&self) -> String {
        format!("{:?}", self)
    }

    /// Returns `self` in the compressed `PublicKeyBytes` representation.
    pub fn compress(&self) -> GenericPublicKeyBytes<Pub> {
        GenericPublicKeyBytes::from(self)
    }

    /// Serialize `self` as compressed bytes.
    pub fn serialize(&self) -> [u8; PUBLIC_KEY_BYTES_LEN] {
        self.point.serialize()
    }

    /// Deserialize `self` from compressed bytes.
    pub fn deserialize(bytes: &[u8]) -> Result<Self, Error> {
        if bytes == &INFINITY_PUBLIC_KEY[..] {
            Err(Error::InvalidInfinityPublicKey)
        } else {
            Ok(Self {
                point: Pub::deserialize(bytes)?,
            })
        }
    }
}

impl<Pub: TPublicKey> Eq for GenericPublicKey<Pub> {}

impl<Pub: TPublicKey> PartialEq for GenericPublicKey<Pub> {
    fn eq(&self, other: &Self) -> bool {
        self.serialize()[..] == other.serialize()[..]
    }
}

/// Hashes the `self.serialize()` bytes.
impl<Pub: TPublicKey> Hash for GenericPublicKey<Pub> {
    fn hash<H: Hasher>(&self, state: &mut H) {
        self.serialize()[..].hash(state);
    }
}

impl<Pub: TPublicKey> Encode for GenericPublicKey<Pub> {
    impl_ssz_encode!(PUBLIC_KEY_BYTES_LEN);
}

impl<Pub: TPublicKey> Decode for GenericPublicKey<Pub> {
    impl_ssz_decode!(PUBLIC_KEY_BYTES_LEN);
}

impl<Pub: TPublicKey> TreeHash for GenericPublicKey<Pub> {
    impl_tree_hash!(PUBLIC_KEY_BYTES_LEN);
}

impl<Pub: TPublicKey> fmt::Display for GenericPublicKey<Pub> {
    impl_display!();
}

impl<Pub: TPublicKey> std::str::FromStr for GenericPublicKey<Pub> {
    impl_from_str!();
}

impl<Pub: TPublicKey> Serialize for GenericPublicKey<Pub> {
    impl_serde_serialize!();
}

impl<'de, Pub: TPublicKey> Deserialize<'de> for GenericPublicKey<Pub> {
    impl_serde_deserialize!();
}

impl<Pub: TPublicKey> fmt::Debug for GenericPublicKey<Pub> {
    impl_debug!();
}

#[cfg(feature = "arbitrary")]
impl<Pub: TPublicKey + 'static> arbitrary::Arbitrary<'_> for GenericPublicKey<Pub> {
    impl_arbitrary!(PUBLIC_KEY_BYTES_LEN);
}


text:
Puppet::Type.type(:a2mod).provide(:debian) do
    desc "Manage Apache 2 modules on Debian-like OSes (e.g. Ubuntu)"

    commands :encmd => "a2enmod"
    commands :discmd => "a2dismod"

    defaultfor :operatingsystem => [:debian, :ubuntu]

    def create
        encmd resource[:name]
    end

    def destroy
        discmd resource[:name]
    end

    def exists?
        mod= "/etc/apache2/mods-enabled/" + resource[:name] + ".load"
        File.exists?(mod)
    end
end


text:
<?php

namespace App\Billing;

interface GatewayInterface
{
    /**
     * Charge a card.
     *
     * @param array $data The attributes for the charge
     *
     * @return \Stripe\Charge
     */
    public function charge(array $data, array $meta = []);
}


text:
package de.flapdoodle.transition.initlike;

import de.flapdoodle.transition.StateID;

public interface InitOnStateTearDown {
	<T> void onStateTearDown(StateID<T> state, T value);
}


text:
using System.Drawing;
using System.Windows.Forms;
using TGC.Core.BoundingVolumes;
using TGC.Core.Collision;
using TGC.Core.Direct3D;
using TGC.Core.Geometry;
using TGC.Core.Input;
using TGC.Core.Mathematica;
using TGC.Core.SceneLoader;
using TGC.Core.Textures;
using TGC.Examples.Example;
using TGC.Examples.UserControls;

namespace TGC.Examples.Transformations
{
    /// <summary>
    ///     Trackball usando Quaternions
    /// </summary>
    public class EjemploTrackball : TGCExampleViewer
    {
        private readonly float radius = 10.0f;

        private TGCQuaternion stacked;
        private TGCMatrix baseSharkTransform;

        private TgcBoundingSphere boundingSphere;

        private TGCSphere sphere;
        private TgcMesh shark;

        private TgcPickingRay pickingRay;

        private TGCVector3 fromDrag;
        private TGCVector3 normalizedFrom;
        private TGCVector3 currentPick;
        private bool dragging;

        private TgcArrow fromArrow;
        private TgcArrow toArrow;
        private TgcArrow crossArrow;

        public EjemploTrackball(string mediaDir, string shadersDir, TgcUserVars userVars, Panel modifiersPanel)
            : base(mediaDir, shadersDir, userVars, modifiersPanel)
        {
            Category = "Transformations";
            Name = "Trackball usando Quaternion";
            Description = "Trackball usando Quaternion";
        }

        public override void Init()
        {
            stacked = TGCQuaternion.Identity;
            fromDrag = TGCVector3.Empty;
            dragging = false;
            currentPick = TGCVector3.Empty;

            InitializeSphere();
            InitializeShark();
            InitializeArrows();

            pickingRay = new TgcPickingRay(Input);

            Camera.SetCamera(new TGCVector3(20f, 0f, 20f), new TGCVector3(-1f, 0f, -1f));
        }

        public override void Update()
        {
            currentPick = PerformPicking();

            if (PickingInsideSphere())
            {
                if (dragging)
                {
                    TGCVector3 normalizedTo = currentPick;
                    normalizedTo.Normalize();

                    var cross = TGCVector3.Cross(normalizedFrom, normalizedTo);
                    var newRotation = TGCQuaternion.RotationAxis(cross, FastMath.Acos(TGCVector3.Dot(normalizedFrom, normalizedTo)));
                    var currentRotation = TGCQuaternion.Multiply(stacked, newRotation);

                    shark.Transform = baseSharkTransform * TGCMatrix.RotationTGCQuaternion(currentRotation);

                    if (Input.buttonUp(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                    {
                        stacked = currentRotation;
                        shark.Transform = baseSharkTransform * TGCMatrix.RotationTGCQuaternion(stacked);
                        dragging = false;
                    }
                }
                else if (Input.buttonPressed(TgcD3dInput.MouseButtons.BUTTON_LEFT))
                {
                    dragging = true;
                    fromDrag = currentPick;
                    normalizedFrom = TGCVector3.Normalize(fromDrag);
                }
            }

            UpdateArrows();
        }

        public override void Render()
        {
            PreRender();
            shark.Render();
            fromArrow.Render();
            toArrow.Render();
            crossArrow.Render();
            sphere.Render();
            PostRender();
        }

        public override void Dispose()
        {
            boundingSphere.Dispose();
            sphere.Dispose();
            shark.Dispose();
        }

        private bool PickingInsideSphere()
        {
            return currentPick.LengthSq() > 0.0f;
        }

        private TGCVector3 PerformPicking()
        {
            pickingRay.updateRay();
            var ray = pickingRay.Ray;
            float distance = 0.0f;
            TGCVector3 point = TGCVector3.Empty;
            TgcCollisionUtils.intersectRaySphere(ray, boundingSphere, out distance, out point);
            return point;
        }

        private void InitializeShark()
        {
            var loader = new TgcSceneLoader();
            var scene = loader.loadSceneFromFile(MediaDir + "Aquatic\\Meshes\\shark-TgcScene.xml");
            shark = scene.Meshes[0];

            TGCVector3 rotationDirection = TGCVector3.Up;
            rotationDirection.Normalize();
            float angle = FastMath.QUARTER_PI / 2.0f;

            baseSharkTransform = TGCMatrix.Scaling(new TGCVector3(0.08f, 0.08f, 0.08f)) * TGCMatrix.RotationTGCQuaternion(new TGCQuaternion(0.0f, FastMath.Sin(angle), 0.0f, FastMath.Cos(angle)));

            shark.Transform = baseSharkTransform;
        }

        private void InitializeSphere()
        {
            var transparentTexture = TgcTexture.createTexture(D3DDevice.Instance.Device, MediaDir + "Texturas\\transparent.png");

            boundingSphere = new TgcBoundingSphere(TGCVector3.Empty, radius);

            sphere = new TGCSphere(1.0f, transparentTexture, TGCVector3.Empty);
            sphere.AlphaBlendEnable = true;
            sphere.updateValues();
            sphere.Transform = TGCMatrix.Scaling(new TGCVector3(radius, radius, radius));
        }

        private void InitializeArrows()
        {
            fromArrow = new TgcArrow();
            fromArrow.BodyColor = Color.DarkBlue;
            fromArrow.HeadColor = Color.Blue;
            fromArrow.HeadSize = new TGCVector2(0.2f, 0.2f);
            fromArrow.Thickness = 0.1f;
            fromArrow.PStart = TGCVector3.Empty;

            toArrow = new TgcArrow();
            toArrow.BodyColor = Color.DarkRed;
            toArrow.HeadColor = Color.Red;
            toArrow.HeadSize = new TGCVector2(0.2f, 0.2f);
            toArrow.Thickness = 0.1f;
            toArrow.PStart = TGCVector3.Empty;

            crossArrow = new TgcArrow();
            crossArrow.BodyColor = Color.DarkGoldenrod;
            crossArrow.HeadColor = Color.Yellow;
            crossArrow.HeadSize = new TGCVector2(0.2f, 0.2f);
            crossArrow.Thickness = 0.1f;
            crossArrow.PStart = TGCVector3.Empty;
        }

        private void UpdateArrows()
        {
            if (dragging)
            {
                toArrow.PEnd = currentPick;
                toArrow.updateValues();

                var cross = TGCVector3.Cross(fromDrag, currentPick);
                cross.Normalize();
                cross.Scale(-radius);
                crossArrow.PEnd = cross;
                crossArrow.updateValues();
            }
            else
            {
                fromArrow.PEnd = currentPick;
                fromArrow.updateValues();

                toArrow.PEnd = TGCVector3.Empty;
                toArrow.updateValues();

                toArrow.PEnd = TGCVector3.Empty;
                toArrow.updateValues();
            }
        }
    }
}


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">

<title>LocalDirectoryStream (Xenon 1.1.0 API for Xenon developers)</title>
<meta name="date" content="2015-12-16">
<link rel="stylesheet" type="text/css" href="../../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

nl.esciencecenter.xenon.adaptors.local

Class LocalDirectoryStream

java.lang.Object

nl.esciencecenter.xenon.adaptors.local.LocalDirectoryStream

All Implemented Interfaces:

java.io.Closeable, java.lang.AutoCloseable, java.lang.Iterable<Path>, java.util.Iterator<Path>, DirectoryStream<Path>

 class LocalDirectoryStream
extends java.lang.Object
implements DirectoryStream<Path>, java.util.Iterator<Path>

LocalDirectoryStream implements a DirectoryStream for local directories.

Since:

1.0

Nested Class Summary

Nested classes/interfaces inherited from interface nl.esciencecenter.xenon.files.DirectoryStream

DirectoryStream.Filter

Field Summary

Fields

Modifier and Type
Field and Description

private Path
dir

The directory to produce a stream for.

private DirectoryStream.Filter
filter

The filter to use.

private java.util.Iterator<java.nio.file.Path>
iterator

The Iterator from the underlying java.nio implementation.

private Path
readAhead

A buffer to read ahead.

private java.nio.file.DirectoryStream<java.nio.file.Path>
stream

The DirectoryStream from the underlying java.nio implementation

Constructor Summary

Constructors

Constructor and Description

LocalDirectoryStream(Path dir,
                    DirectoryStream.Filter filter)

Method Summary

Methods

Modifier and Type
Method and Description

void
close()

private Path
getPath(java.nio.file.Path path)

boolean
hasNext()

java.util.Iterator<Path>
iterator()

Path
next()

void
remove()

Methods inherited from class java.lang.Object

clone, equals, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Field Detail

stream

private final java.nio.file.DirectoryStream<java.nio.file.Path> stream

The DirectoryStream from the underlying java.nio implementation

iterator

private final java.util.Iterator<java.nio.file.Path> iterator

The Iterator from the underlying java.nio implementation.

filter

private final DirectoryStream.Filter filter

The filter to use.

dir

private final Path dir

The directory to produce a stream for.

readAhead

private Path readAhead

A buffer to read ahead.

Constructor Detail

LocalDirectoryStream

LocalDirectoryStream(Path dir,
                    DirectoryStream.Filter filter)
               throws XenonException

Throws:

XenonException

Method Detail

getPath

private Path getPath(java.nio.file.Path path)

iterator

public java.util.Iterator<Path> iterator()

Specified by:

iterator in interface java.lang.Iterable<Path>

Specified by:

iterator in interface DirectoryStream<Path>

close

public void close()
           throws java.io.IOException

Specified by:

close in interface java.io.Closeable

Specified by:

close in interface java.lang.AutoCloseable

Specified by:

close in interface DirectoryStream<Path>

Throws:

java.io.IOException

hasNext

public boolean hasNext()

Specified by:

hasNext in interface java.util.Iterator<Path>

next

public Path next()

Specified by:

next in interface java.util.Iterator<Path>

remove

public void remove()

Specified by:

remove in interface java.util.Iterator<Path>

Overview

Package

Class

Tree

Deprecated

Index

Help

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method


text: Included are the solutions for problems from Elements of Programming Interviews.


text:
package com.study.callbankdata;

import android.content.ContentResolver;
import android.content.ContentValues;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.view.View;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

public class MainActivity extends AppCompatActivity {

    @Bind(R.id.btn_insert)
    Button btnInsert;
    @Bind(R.id.btn_delete)
    Button btnDelete;
    @Bind(R.id.btn_update)
    Button btnUpdate;
    @Bind(R.id.btn_search)
    Button btnSearch;
    @Bind(R.id.activity_main)
    LinearLayout activityMain;
    @Bind(R.id.tv_result)
    TextView tvResult;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ButterKnife.bind(this);
    }

    @OnClick({R.id.btn_insert, R.id.btn_delete, R.id.btn_update, R.id.btn_search})
    public void onClick(View view) {
        ContentResolver resolver = getContentResolver();
        Uri url = Uri.parse("content://com.study.bankdb/account");

        switch (view.getId()) {
            case R.id.btn_insert:
                ContentValues insertValues = new ContentValues();
                insertValues.put("name", "danke");
                insertValues.put("money", "100");
                Uri uri = resolver.insert(url, insertValues);
                if (uri != null) {
                    Toast.makeText(this, "添加成功,添加到第" + uri.toString() + "条数据", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "添加失败", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_delete:
                int deleteResult = resolver.delete(url, "name=?", new String[]{"danke"});
                if (deleteResult >= 0) {
                    Toast.makeText(this, "删除了" + deleteResult + "条数据", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "删除失败", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_update:
                ContentValues updateValues = new ContentValues();
                updateValues.put("money", 200);
                int updateResult = resolver.update(url, updateValues, "name=?", new String[]{"danke"});
                if (updateResult >= 0) {
                    Toast.makeText(this, "修改了" + updateResult + "条数据", Toast.LENGTH_SHORT).show();
                } else {
                    Toast.makeText(this, "修改失败", Toast.LENGTH_SHORT).show();
                }
                break;
            case R.id.btn_search:
                Cursor cursor = resolver.query(url, new String[]{"name", "money"}, null, null, null);
                if (cursor != null) {
                    StringBuilder sb = new StringBuilder();
                    while (cursor.moveToNext()) {
                        String name = cursor.getString(0);
                        int money = cursor.getInt(1);
                        sb.append("姓名: " + name + ", 金额: " + money + "\r\n");
                    }
                    cursor.close();
                    tvResult.setText(sb.toString());
                }
                break;
        }
    }
}


text:
package testService;

import java.io.IOException;
import java.sql.SQLTimeoutException;
import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.junit.*;
import org.junit.runner.RunWith;

import com.google.api.server.spi.response.NotFoundException;
import com.google.gson.Gson;

import service.SuggestServlet;
import service.Utils;
import db.DBAccess;
import db.DBArtist;
import db.DBOsservazione;
import db.DBRequestSugg;
import db.DBSuggerimento;
import db.DBTag;
import db.DBUser;
import mockit.*;
import mockit.integration.junit4.JMockit;

@RunWith(JMockit.class)
public class SuggestTest {
	@Mocked
	HttpServletRequest mockHttpServletRequest;
	@Mocked
	HttpServletResponse mockHttpServletResponse;

	DBUser testNoArtist, testUserManyArtist;
	DBRequestSugg testWrong1Request, testWrong2Request, testCorrectRequest;
	String jsonNoArtist, jsonUserManyArtist, tagCluster;
	String jsonWrong1Request, jsonWrong2Request, jsonCorrectRequest, jsonResponse, jsonResponse2;
	List<String> dynRules, staRules;
	List<Integer> tagContestuali, tagContestuali2;
	DBSuggerimento tagFinali;

	public SuggestTest(){
		super();
		Gson gson = new Gson();

		// prepare mock Requests
		testWrong1Request = new DBRequestSugg(2);
		testWrong1Request.addOsservazione(new DBOsservazione("temperatura", "5_15"));
		jsonWrong1Request = gson.toJson(testWrong1Request);
		jsonWrong1Request = jsonWrong1Request.replace("[", "");

		testWrong2Request = new DBRequestSugg(2);
		testWrong2Request.addOsservazione(new DBOsservazione("temperatura", "5_15"));
		testWrong2Request.addOsservazione(new DBOsservazione("Condizioni_meteo", "Temporale"));
		testWrong2Request.addOsservazione(new DBOsservazione("mezzo", "Auto"));
		testWrong2Request.addOsservazione(new DBOsservazione("Km_to_run", "10_30"));
		testWrong2Request.addOsservazione(new DBOsservazione("Momento_viaggio", "Giorno_feriale"));

		jsonWrong2Request = gson.toJson(testWrong2Request);

		testCorrectRequest = new DBRequestSugg(2);
		testCorrectRequest.addOsservazione(new DBOsservazione("Temperatura", "5_15"));
		testCorrectRequest.addOsservazione(new DBOsservazione("Condizioni_meteo", "Pioggia"));
		testCorrectRequest.addOsservazione(new DBOsservazione("Mezzo", "Moto"));
		testCorrectRequest.addOsservazione(new DBOsservazione("Km_to_run", "maj100"));
		testCorrectRequest.addOsservazione(new DBOsservazione("Momento_viaggio", "Notte_festivo"));

		jsonCorrectRequest = gson.toJson(testCorrectRequest);

		// prepare Mock DB users
		testNoArtist = new DBUser(2,"carlo");
		jsonNoArtist = gson.toJson(testNoArtist);

		testUserManyArtist = new DBUser(2,"carlo");
		testUserManyArtist.addArtists(new DBArtist(1, "883"));
		testUserManyArtist.addArtists(new DBArtist(2, "Queen"));
		testUserManyArtist.addArtists(new DBArtist(3, "Edoardo Bennato"));
		testUserManyArtist.addArtists(new DBArtist(4, "Pooh"));
		jsonUserManyArtist = gson.toJson(testUserManyArtist);

		// prepare mock rules
		tagCluster = "Ballabile";
		dynRules = new ArrayList<String>();
		dynRules.add("(defrule DepositoCluster  (Result_Tag_cluster (Tag_cluster ?tc) (Reliability ?r)) => (store \"Tag_cluster\" ?tc))");
		dynRules.add("(deftemplate Result_Mood_meteo (slot Mood_meteo) (slot Reliability) )");
		dynRules.add("(deftemplate Result_Travel_mood (slot Travel_mood) (slot Reliability) )");
		dynRules.add("(deftemplate Result_Tag_cluster (slot Tag_cluster) (slot Reliability) )");

		dynRules.add("(defrule Tag_clusterBallabile5706 (Temperatura 5_15)  (Condizioni_meteo Pioggia) "+
				"(Mezzo Moto)  (Km_to_run maj100)  (Momento_viaggio Notte_festivo) => " +
				"(assert (Result_Tag_cluster (Tag_cluster Ballabile) (Reliability 0.5308778496087105))) )");

		dynRules.add("(defrule Mood_meteoTriste1866 (Temperatura 5_15)  (Condizioni_meteo Pioggia) "+
				"(Mezzo Moto)  (Km_to_run maj100)  (Momento_viaggio Notte_festivo) =>" +
				"(assert (Result_Mood_meteo (Mood_meteo Triste) (Reliability 0.5384615384615385))) )");

		dynRules.add("(defrule Tag_clusterBallabile5706 (Temperatura 5_15)  (Condizioni_meteo Pioggia) "+
				"(Mezzo Moto)  (Km_to_run maj100)  (Momento_viaggio Notte_festivo) => " +
				"(assert (Result_Tag_cluster (Tag_cluster Ballabile) (Reliability 0.5308778496087105))) )");

		staRules = new ArrayList<String>();
		staRules.add("(defrule ArtistToArtistRule1 (Artist 2) => (assert (Tag 14,15,104,374,507,559,2143))) ");

		// prepare mock tag from cluster
		tagContestuali = new ArrayList<Integer>();
		tagContestuali.add(150);
		tagContestuali.add(149);
		tagContestuali.add(1024);
		tagContestuali.add(15);
		tagContestuali.add(304);

		tagContestuali2 = new ArrayList<Integer>();
		tagContestuali2.add(150);
		tagContestuali2.add(149);
		tagContestuali2.add(1024);
		tagContestuali2.add(304);

		tagFinali = new DBSuggerimento();
		tagFinali.addTag(new DBTag(15));
		jsonResponse = gson.toJson(tagFinali);

		tagFinali = new DBSuggerimento();
		tagFinali.addTag(new DBTag(14));
		tagFinali.addTag(new DBTag(150));
		jsonResponse2 = gson.toJson(tagFinali);
	}

	@Test
	public void testSuggestSuccess() throws IOException {
		new MockUp<Utils>() {
			@Mock
			private String readText(HttpServletRequest request) {
				return jsonCorrectRequest;
			}
		};

		new MockUp<DBAccess>() {
			@Mock
			public DBUser getUserInfo(int id){
				Assert.assertEquals(testUserManyArtist.getId(), id);
				return testUserManyArtist;
			}
			@Mock
			public List<String> getRules(int idNet, int idUser, boolean dynamic){
				Assert.assertEquals(testUserManyArtist.getId(), idUser);
				if (dynamic)
					return dynRules;
				else
					return staRules;
			}
			@Mock
			public List<Integer> getTags(String cluster){
				Assert.assertEquals(cluster, tagCluster);
				return tagContestuali;
			}
		};

		new Expectations() {
			{
				//mockHttpServletRequest.getContentType(); returns(Utils.jsonType);

				mockHttpServletResponse.setContentType(Utils.jsonType);
				mockHttpServletResponse.addHeader("cluster", tagCluster);
				mockHttpServletResponse.getWriter().print(jsonResponse);
			}
		};

		SuggestServlet serv = new SuggestServlet();
		try {
			serv.doPost(mockHttpServletRequest, mockHttpServletResponse);
		} catch (IOException e) { Assert.fail(); }
	}

	@Test
	public void testSuggestNoIntersectionSuccess() throws IOException {
		new MockUp<Utils>() {
			@Mock
			private String readText(HttpServletRequest request) {
				return jsonCorrectRequest;
			}
		};

		new MockUp<DBAccess>() {
			@Mock
			public DBUser getUserInfo(int id){
				Assert.assertEquals(testUserManyArtist.getId(), id);
				return testUserManyArtist;
			}
			@Mock
			public List<String> getRules(int idNet, int idUser, boolean dynamic){
				Assert.assertEquals(testUserManyArtist.getId(), idUser);
				if (dynamic)
					return dynRules;
				else
					return staRules;
			}
			@Mock
			public List<Integer> getTags(String cluster){
				Assert.assertEquals(cluster, tagCluster);
				return tagContestuali2;
			}
		};

		new Expectations() {
			{
				//mockHttpServletRequest.getContentType(); returns(Utils.jsonType);

				mockHttpServletResponse.setContentType(Utils.jsonType);
				mockHttpServletResponse.addHeader("cluster", tagCluster);
				mockHttpServletResponse.getWriter().print(jsonResponse2);
			} //"[{\"tagSuggeriti\":[{\"id\":14},{\"id\":150}]}]"
		};

		SuggestServlet serv = new SuggestServlet();
		try {
			serv.doPost(mockHttpServletRequest, mockHttpServletResponse);
		} catch (IOException e) { Assert.fail(); }
	}

	@Test
	public void testNoArtist() throws IOException {
		new MockUp<Utils>() {
			@Mock
			private String readText(HttpServletRequest request) {
				return jsonCorrectRequest;
			}
		};

		new MockUp<DBAccess>() {
			@Mock
			public DBUser getUserInfo(int id){
				Assert.assertEquals(testNoArtist.getId(), id);
				return testNoArtist;
			}
			@Mock
			public List<String> getRules(int idNet, int idUser, boolean dynamic){
				Assert.fail();
				return dynRules;
			}
		};

		new Expectations() {
			{
				//mockHttpServletRequest.getContentType(); returns(Utils.jsonType);

				mockHttpServletResponse.setContentType(Utils.htmlType);
				mockHttpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				mockHttpServletResponse.getWriter().print(anyString);
			}
		};

		SuggestServlet serv = new SuggestServlet();
		try {
			serv.doPost(mockHttpServletRequest, mockHttpServletResponse);
		} catch (IOException e) { Assert.fail(); }
	}

	@Test
	public void testDBNotConnected() throws IOException {
		new MockUp<Utils>() {
			@Mock
			private String readText(HttpServletRequest request) {
				return jsonCorrectRequest;
			}
		};

		new MockUp<DBAccess>() {
			@Mock
			public DBUser getUserInfo(int id) throws SQLTimeoutException{
				throw new SQLTimeoutException();
			}
			@Mock
			public List<String> getRules(int idNet, int idUser, boolean dynamic){
				Assert.fail();
				return dynRules;
			}
		};

		new Expectations() {
			{
				//mockHttpServletRequest.getContentType(); returns(Utils.jsonType);

				mockHttpServletResponse.setContentType(Utils.htmlType);
				mockHttpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				mockHttpServletResponse.getWriter().print(anyString);
			}
		};

		SuggestServlet serv = new SuggestServlet();
		try {
			serv.doPost(mockHttpServletRequest, mockHttpServletResponse);
		} catch (IOException e) { Assert.fail(); }
	}

	@Test
	public void testTagClusterVuoto() throws IOException {
		new MockUp<Utils>() {
			@Mock
			private String readText(HttpServletRequest request) {
				return jsonCorrectRequest;
			}
		};

		new MockUp<DBAccess>() {
			@Mock
			public DBUser getUserInfo(int id){
				Assert.assertEquals(testUserManyArtist.getId(), id);
				return testUserManyArtist;
			}
			@Mock
			public List<String> getRules(int idNet, int idUser, boolean dynamic){
				Assert.assertEquals(testUserManyArtist.getId(), idUser);
				if (dynamic)
					return dynRules;
				else
					return staRules;
			}
			@Mock
			public List<Integer> getTags(String cluster) throws IllegalArgumentException{
				throw new IllegalArgumentException();
			}
		};

		new Expectations() {
			{
				//mockHttpServletRequest.getContentType(); returns(Utils.jsonType);

				mockHttpServletResponse.setContentType(Utils.htmlType);
				mockHttpServletResponse.setStatus(HttpServletResponse.SC_INTERNAL_SERVER_ERROR);
				mockHttpServletResponse.getWriter().print(anyString);
			}
		};

		SuggestServlet serv = new SuggestServlet();
		try {
			serv.doPost(mockHttpServletRequest, mockHttpServletResponse);
		} catch (IOException e) { Assert.fail(); }
	}

	@Test
	public void testTagClusterNotFound() throws IOException {
		new MockUp<Utils>() {
			@Mock
			private String readText(HttpServletRequest request) {
				return jsonCorrectRequest;
			}
		};

		new MockUp<DBAccess>() {
			@Mock
			public DBUser getUserInfo(int id){
				Assert.assertEquals(testUserManyArtist.getId(), id);
				return testUserManyArtist;
			}
			@Mock
			public List<String> getRules(int idNet, int idUser, boolean dynamic){
				Assert.assertEquals(testUserManyArtist.getId(), idUser);
				if (dynamic)
					return dynRules;
				else
					return staRules;
			}
			@Mock
			public List<Integer> getTags(String cluster) throws NotFoundException{
				throw new NotFoundException("");
			}
		};

		new Expectations() {
			{
				//mockHttpServletRequest.getContentType(); returns(Utils.jsonType);

				mockHttpServletResponse.setContentType(Utils.htmlType);
				mockHttpServletResponse.setStatus(HttpServletResponse.SC_NOT_FOUND);
				mockHttpServletResponse.getWriter().print(anyString);
			}
		};

		SuggestServlet serv = new SuggestServlet();
		try {
			serv.doPost(mockHttpServletRequest, mockHttpServletResponse);
		} catch (IOException e) { Assert.fail(); }
	}

	@Test
	public void testWrongJson1() throws IOException {
		new MockUp<Utils>() {
			@Mock
			private String readText(HttpServletRequest request) {
				System.out.print(jsonWrong1Request);
				return jsonWrong1Request;
			}
		};

		new MockUp<DBAccess>() {
			@Mock
			public DBUser getUserInfo(int id){
				Assert.fail();
				return testUserManyArtist;
			}
		};

		new Expectations() {
			{
				//mockHttpServletRequest.getContentType(); returns(Utils.jsonType);

				mockHttpServletResponse.setContentType(Utils.htmlType);
				mockHttpServletResponse.setStatus(HttpServletResponse.SC_BAD_REQUEST);
				mockHttpServletResponse.getWriter().print(anyString);
			}
		};

		SuggestServlet serv = new SuggestServlet();
		try {
			serv.doPost(mockHttpServletRequest, mockHttpServletResponse);
		} catch (IOException e) { Assert.fail(); }
	}
}


text: createBundle(bundle, NODE_DEV);


text:
<?php

namespace Symfony\Component\DependencyInjection\Compiler;

use Symfony\Component\DependencyInjection\ChildDefinition;
use Symfony\Component\DependencyInjection\Definition;
use Symfony\Component\DependencyInjection\Exception\ExceptionInterface;
use Symfony\Component\DependencyInjection\Exception\RuntimeException;

/**
 * This replaces all ChildDefinition instances with their equivalent fully
 * merged Definition instance.
 *
 * @author Johannes M. Schmitt <schmittjoh@gmail.com>
 * @author Nicolas Grekas <p@tchwork.com>
 */
class ResolveChildDefinitionsPass extends AbstractRecursivePass
{
    protected function processValue($value, $isRoot = false)
    {
        if (!$value instanceof Definition) {
            return parent::processValue($value, $isRoot);
        }
        if ($isRoot) {
            // yes, we are specifically fetching the definition from the
            // container to ensure we are not operating on stale data
            $value = $this->container->getDefinition($this->currentId);
        }
        if ($value instanceof ChildDefinition) {
            $value = $this->resolveDefinition($value);
            if ($isRoot) {
                $this->container->setDefinition($this->currentId, $value);
            }
        }

        return parent::processValue($value, $isRoot);
    }

    /**
     * Resolves the definition.
     *
     * @return Definition
     *
     * @throws RuntimeException When the definition is invalid
     */
    private function resolveDefinition(ChildDefinition $definition)
    {
        try {
            return $this->doResolveDefinition($definition);
        } catch (ExceptionInterface $e) {
            $r = new \ReflectionProperty($e, 'message');
            $r->setAccessible(true);
            $r->setValue($e, sprintf('Service "%s": %s', $this->currentId, $e->getMessage()));

            throw $e;
        }
    }

    private function doResolveDefinition(ChildDefinition $definition)
    {
        if (!$this->container->has($parent = $definition->getParent())) {
            throw new RuntimeException(sprintf('Parent definition "%s" does not exist.', $parent));
        }

        $parentDef = $this->container->findDefinition($parent);
        if ($parentDef instanceof ChildDefinition) {
            $id = $this->currentId;
            $this->currentId = $parent;
            $parentDef = $this->resolveDefinition($parentDef);
            $this->container->setDefinition($parent, $parentDef);
            $this->currentId = $id;
        }

        $this->container->log($this, sprintf('Resolving inheritance for "%s" (parent: %s).', $this->currentId, $parent));
        $def = new Definition();

        // merge in parent definition
        // purposely ignored attributes: abstract, shared, tags, autoconfigured
        $def->setClass($parentDef->getClass());
        $def->setArguments($parentDef->getArguments());
        $def->setMethodCalls($parentDef->getMethodCalls());
        $def->setProperties($parentDef->getProperties());
        if ($parentDef->isDeprecated()) {
            $def->setDeprecated(true, $parentDef->getDeprecationMessage('%service_id%'));
        }
        $def->setFactory($parentDef->getFactory());
        $def->setConfigurator($parentDef->getConfigurator());
        $def->setFile($parentDef->getFile());
        $def->setPublic($parentDef->isPublic());
        $def->setLazy($parentDef->isLazy());
        $def->setAutowired($parentDef->isAutowired());
        $def->setChanges($parentDef->getChanges());

        $def->setBindings($definition->getBindings() + $parentDef->getBindings());

        // overwrite with values specified in the decorator
        $changes = $definition->getChanges();
        if (isset($changes['class'])) {
            $def->setClass($definition->getClass());
        }
        if (isset($changes['factory'])) {
            $def->setFactory($definition->getFactory());
        }
        if (isset($changes['configurator'])) {
            $def->setConfigurator($definition->getConfigurator());
        }
        if (isset($changes['file'])) {
            $def->setFile($definition->getFile());
        }
        if (isset($changes['public'])) {
            $def->setPublic($definition->isPublic());
        } else {
            $def->setPrivate($definition->isPrivate() || $parentDef->isPrivate());
        }
        if (isset($changes['lazy'])) {
            $def->setLazy($definition->isLazy());
        }
        if (isset($changes['deprecated'])) {
            $def->setDeprecated($definition->isDeprecated(), $definition->getDeprecationMessage('%service_id%'));
        }
        if (isset($changes['autowired'])) {
            $def->setAutowired($definition->isAutowired());
        }
        if (isset($changes['shared'])) {
            $def->setShared($definition->isShared());
        }
        if (isset($changes['decorated_service'])) {
            $decoratedService = $definition->getDecoratedService();
            if (null === $decoratedService) {
                $def->setDecoratedService($decoratedService);
            } else {
                $def->setDecoratedService($decoratedService[0], $decoratedService[1], $decoratedService[2]);
            }
        }

        // merge arguments
        foreach ($definition->getArguments() as $k => $v) {
            if (is_numeric($k)) {
                $def->addArgument($v);
            } elseif (0 === strpos($k, 'index_')) {
                $def->replaceArgument((int) substr($k, strlen('index_')), $v);
            } else {
                $def->setArgument($k, $v);
            }
        }

        // merge properties
        foreach ($definition->getProperties() as $k => $v) {
            $def->setProperty($k, $v);
        }

        // append method calls
        if ($calls = $definition->getMethodCalls()) {
            $def->setMethodCalls(array_merge($def->getMethodCalls(), $calls));
        }

        foreach (array_merge($parentDef->getErrors(), $definition->getErrors()) as $v) {
            $def->addError($v);
        }

        // these attributes are always taken from the child
        $def->setAbstract($definition->isAbstract());
        $def->setTags($definition->getTags());
        // autoconfigure is never taken from parent (on purpose)
        // and it's not legal on an instanceof
        $def->setAutoconfigured($definition->isAutoconfigured());

        return $def;
    }
}


text:
package org.springframework.cloud.sleuth.instrument.web;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.springframework.cloud.sleuth.Trace;
import org.springframework.cloud.sleuth.TraceManager;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

/**
 * @author Spencer Gibb
 */
public class TraceHandlerInterceptor implements HandlerInterceptor {

	private static final String ATTR_NAME = "__CURRENT_TRACE_HANDLER_TRACE_ATTR___";

	private final TraceManager traceManager;

	public TraceHandlerInterceptor(TraceManager traceManager) {
		this.traceManager = traceManager;
	}

	@Override
	public boolean preHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler) throws Exception {
		// TODO: get trace data from request?
		// TODO: what is the description?
		Trace trace = this.traceManager.startSpan("traceHandlerInterceptor");
		request.setAttribute(ATTR_NAME, trace);
		return true;
	}

	@Override
	public void postHandle(HttpServletRequest request, HttpServletResponse response,
			Object handler, ModelAndView modelAndView) throws Exception {

	}

	@Override
	public void afterCompletion(HttpServletRequest request, HttpServletResponse response,
			Object handler, Exception ex) throws Exception {
		Trace trace = Trace.class.cast(request.getAttribute(ATTR_NAME));
		this.traceManager.close(trace);
	}
}