text:
package org.camunda.bpm.demo.invoice.ui.diagram;

import java.util.ArrayList;
import java.util.List;

import javax.inject.Inject;
import javax.inject.Named;

import org.camunda.bpm.engine.HistoryService;
import org.camunda.bpm.engine.RepositoryService;
import org.camunda.bpm.engine.RuntimeService;
import org.camunda.bpm.engine.TaskService;
import org.camunda.bpm.engine.cdi.BusinessProcess;
import org.camunda.bpm.engine.history.HistoricActivityInstance;
import org.camunda.bpm.engine.history.HistoricTaskInstance;
import org.camunda.bpm.engine.repository.DiagramLayout;
import org.camunda.bpm.engine.repository.DiagramNode;
import org.camunda.bpm.engine.runtime.ProcessInstance;
import org.camunda.bpm.engine.task.Comment;

@Named
public class ProcessDiagramController {

  @Inject
  private RuntimeService runtimeService;

  @Inject
  private RepositoryService repositoryService;

  @Inject
  private HistoryService historyService;

  @Inject
  private BusinessProcess businessProcess;

  @Inject
  private TaskService taskService;

  private ProcessInstance getCurrentProcessInstance() {
    return businessProcess.getProcessInstance();
  }

  public List<PositionedHistoricActivityInstance> getTraversedFlowNodes() {
    ArrayList<PositionedHistoricActivityInstance> alist = new ArrayList<PositionedHistoricActivityInstance>();

    ProcessInstance processInstance = getCurrentProcessInstance();

    if (processInstance != null) {
      DiagramLayout processDiagramLayout = repositoryService.getProcessDiagramLayout(processInstance.getProcessDefinitionId());

      List<HistoricActivityInstance> hlist = historyService.createHistoricActivityInstanceQuery().processInstanceId(processInstance.getId()).list();

      for (HistoricActivityInstance hact : hlist) {
        if (hact.getEndTime() != null) {
           PositionedHistoricActivityInstance pact = new PositionedHistoricActivityInstance(hact, processDiagramLayout.getNode(hact.getActivityId()));
          alist.add(pact);

        }
      }
    }

    return alist;
  }

  public List<PositionedHistoricTaskInstance> getTraversedTasks() {
	  	ArrayList<PositionedHistoricTaskInstance> alist = new ArrayList<PositionedHistoricTaskInstance>();
	    ProcessInstance processInstance = getCurrentProcessInstance();

	    if (processInstance != null) {
	      DiagramLayout processDiagramLayout = repositoryService.getProcessDiagramLayout(processInstance.getProcessDefinitionId());
	      List<HistoricTaskInstance> hlist = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).orderByHistoricActivityInstanceStartTime().asc().list();
	      for (HistoricTaskInstance htask : hlist) {
	    	  if (htask.getEndTime() != null) {
	        	PositionedHistoricTaskInstance ptask = new PositionedHistoricTaskInstance(htask, processDiagramLayout.getNode(htask.getTaskDefinitionKey()));
	        	alist.add(ptask);
	        }
	      }
	    }
	    return alist;
	  }

  public List<PositionedHistoricTaskDefinition> getTraversedTaskDefinitions() {
	  	ArrayList<PositionedHistoricTaskDefinition> alist = new ArrayList<PositionedHistoricTaskDefinition>();

	    ProcessInstance processInstance = getCurrentProcessInstance();

	    if (processInstance != null) {
	      DiagramLayout processDiagramLayout = repositoryService.getProcessDiagramLayout(processInstance.getProcessDefinitionId());

	      //order by taskName as workaround because orderByTaskDefinitionKey is not working. This is not really safe!
	      List<HistoricTaskInstance> hlist = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).orderByTaskName().asc().list();

	      int i=0;
	      for (HistoricTaskInstance htask : hlist) {
	    	  if (htask.getEndTime() != null) {
	    		  if (i>0) {
		    		  if (alist.get(i-1).getTaskDefinitionKey().equals(htask.getTaskDefinitionKey())) {
		        		alist.get(i-1).taskInstances.add(htask);
		        	} else {
		        		PositionedHistoricTaskDefinition ptask = new PositionedHistoricTaskDefinition(htask, processDiagramLayout.getNode(htask.getTaskDefinitionKey()));
		  	          	alist.add(ptask);
		  	          	i++;
		        	}
	    		  } else {
		        		PositionedHistoricTaskDefinition ptask = new PositionedHistoricTaskDefinition(htask, processDiagramLayout.getNode(htask.getTaskDefinitionKey()));
		  	          	alist.add(ptask);
		  	          	i++;
	    		  }
	        }
	      }
	    }
	    return alist;
	  }

  public List<DiagramNode> getActiveActivityBoundsOfLatestProcessInstance() {
    ArrayList<DiagramNode> list = new ArrayList<DiagramNode>();
    ProcessInstance processInstance = getCurrentProcessInstance();
    if (processInstance != null) {
      DiagramLayout processDiagramLayout = repositoryService.getProcessDiagramLayout(processInstance.getProcessDefinitionId());
      List<String> activeActivityIds = runtimeService.getActiveActivityIds(processInstance.getId());
      for (String activeActivityId : activeActivityIds) {
        list.add(processDiagramLayout.getNode(activeActivityId));
      }
    }
    return list;
  }

  public List<Comment> getCommentsOfLastHistoricTask() {
    ProcessInstance processInstance = getCurrentProcessInstance();
    List<HistoricTaskInstance> hlist = historyService.createHistoricTaskInstanceQuery().processInstanceId(processInstance.getId()).orderByHistoricTaskInstanceEndTime().desc().list();
	if (hlist.get(0).getEndTime() != null) {
	    return getTaskComments(hlist.get(0).getId());
	} else {
		return null;
	}
  }

  public String getTaskComment (String taskId) {
	  String comment = "";
	  if (!taskService.getTaskComments(taskId).isEmpty()) comment = taskService.getTaskComments(taskId).get(0).getFullMessage();
      return comment;
  }

  public List<Comment> getTaskComments (String taskId) {
	  return taskService.getTaskComments(taskId);
  }

}

redpajama_set_name: RedPajamaGithub


text:
require 'spec_helper'

describe Metro::KeyValueCoding do

  class KeyValueCodingObject
    include Metro::KeyValueCoding
    attr_accessor :description, :properties
  end

  subject do
    object = KeyValueCodingObject.new

    object.description = "Describe Yourself"
    object.properties = { height: 100, width: 50 }

    object
  end

  describe "#get" do
    context "when given a key with a single attribute" do
      let(:key) { :description }
      let(:expected_value) { "Describe Yourself" }

      it "should return the value" do
        subject.get(key).should eq expected_value
      end
    end

    context "when given a key with multiple attributes" do
      let(:key) { "properties.keys" }
      let(:expected_value) { [ :height, :width ] }

      it "should return the expected value" do
        subject.get(key).should eq expected_value
      end
    end
  end

  describe "#set" do
    context "when given a key with a single attribute" do
      let(:key) { :description }
      let(:expected_value) { "New Description" }

      it "should set the value" do
        subject.set(key,expected_value)
        subject.get(key).should eq expected_value
      end
    end

    context "when given a key with multiple attributes" do
      let(:key) { "properties.default" }
      let(:expected_value) { 0 }

      it "should set the value" do
        subject.set(key,expected_value)
        subject.get(key).should eq expected_value
      end
    end
  end

end


text:
name: Christopher Lozinski
---


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

<TITLE>
IUseVisitor (Soot API)
</TITLE>

<META NAME="date" CONTENT="2012-01-22">

<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD

soot.jimple.toolkits.typing.fast

Interface IUseVisitor

public interface IUseVisitor

Author:

Ben Bellamy

Method Summary

 boolean
finish()

 Value
visit(Value op,
      Type useType,
      Stmt stmt)

Method Detail

visit

Value visit(Value op,
            Type useType,
            Stmt stmt)

finish

boolean finish()

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  All Classes

  SUMMARY: NESTED | FIELD | CONSTR | METHOD

DETAIL: FIELD | CONSTR | METHOD


text:
#include <qi/macro.hpp>
#include <qi/path.hpp>

#define BOOST_UTF8_BEGIN_NAMESPACE  namespace qi { namespace detail {
#define BOOST_UTF8_END_NAMESPACE    }}
#define BOOST_UTF8_DECL
#include "utf8_codecvt_facet.hpp"
#include "utf8_codecvt_facet_impl.hpp"

namespace qi {

  //this is initialized once.. and will be reported to leak memory.
  //but that okay for a global to be freed by the program termination
  static detail::utf8_codecvt_facet *gUtf8CodecvtFacet = 0;

  codecvt_type &unicodeFacet()
  {
    if (!gUtf8CodecvtFacet)
      gUtf8CodecvtFacet = new detail::utf8_codecvt_facet();
    codecvt_type *ret = gUtf8CodecvtFacet;
    return *ret;
  }

}


text:
static NSString *PHOTO_CELL = @"PHOTO_CELL";

@interface WBPhotosViewController ()
{
    NSDictionary *_postChangedNotificationUserInfo;
    UIActionSheet *_imagePickerActionSheet;
}

@property (nonatomic, strong) UITableView *photoTable;
@property (nonatomic, strong) UIScrollView *contentView;
@property (nonatomic, strong) NSArray *data;
@property (nonatomic, strong) UIImagePickerController * imagePickerController;

@end

@implementation WBPhotosViewController

- (void)viewDidLoad
{
    [super viewDidLoad];

    // fixed bug that navigation bar covers view
    self.navigationController.navigationBar.translucent = NO;
    if ([self respondsToSelector:@selector(edgesForExtendedLayout)])
        self.edgesForExtendedLayout = UIRectEdgeNone;   // iOS 7 specific

    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(respondPostChangedNotification:) name:[WBUtility postChangedNotification] object:nil];

    UIBarButtonItem *cameraBarItem;
    cameraBarItem = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemCamera target:self action:@selector(showImagePickerActionSheet)];
    [self.navigationItem setRightBarButtonItem:cameraBarItem];

    UIActionSheet *imagePickerActionSheet  = [[UIActionSheet alloc] init];
    [imagePickerActionSheet addButtonWithTitle:@"拍照"];
    [imagePickerActionSheet addButtonWithTitle:@"从照片库选"];
    [imagePickerActionSheet addButtonWithTitle:@"退出"];
    [imagePickerActionSheet setCancelButtonIndex:2];
    imagePickerActionSheet.delegate = self;
    _imagePickerActionSheet = imagePickerActionSheet ;

    [self initImagePickerController];

    UITableView *tableView;
    CGPoint viewOrigin = self.view.frame.origin;
    CGSize viewSize = self.view.frame.size;
    CGRect tableFrame = CGRectMake(viewOrigin.x, 0, viewSize.width, viewSize.height);
    tableView = [[UITableView alloc] initWithFrame:tableFrame];
    tableView.dataSource = self;
    tableView.delegate = self;
    tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [tableView registerClass:[WBPhotoTableCell class] forCellReuseIdentifier:PHOTO_CELL];
    [self.view addSubview:tableView];
    self.photoTable = tableView;

    [self.eventHandler updateView];
}

- (void)didReceiveMemoryWarning
{
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
    NSLog(@"Received memory warning --> Photo view controller");
}

- (void)viewWillAppear:(BOOL)animated
{
    //[self.eventHandler updateView];
}

- (void)viewDidAppear:(BOOL)animated
{
    [super viewDidAppear:animated];

    if (_postChangedNotificationUserInfo)
    {
        // refresh table
        [self refreshTableAfterPostChanged];

        _postChangedNotificationUserInfo = nil;
    }
}

- (void)showPosts:(NSArray *)posts
{
    self.data = posts;
    [self.photoTable reloadData];
}

- (void)reload
{
    [self.eventHandler updateView];
}

- (void)respondPostChangedNotification:(NSNotification *)notification
{

    if ([notification.name isEqualToString:[WBUtility postChangedNotification]])
    {
        _postChangedNotificationUserInfo = notification.userInfo;
    }
}

- (void)refreshTableAfterPostChanged
{
    NSString *action = [_postChangedNotificationUserInfo objectForKey:[WBUtility postChangedAction]];
    if ([action isEqualToString:[WBUtility postChangedActionAdd]])
    {
        WBPostItem *addedItem = [_postChangedNotificationUserInfo objectForKey:[WBUtility postChangedItem]];

        if (addedItem.image)
        {
            NSMutableArray *array = [NSMutableArray arrayWithArray:_data];
            [array insertObject:[WBPhotoDisplayItem itemWithPostItem:addedItem scaleSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 250)] atIndex:0];
            _data = array;

            // scroll table to up
            [_photoTable scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:0 inSection:0] atScrollPosition:UITableViewScrollPositionTop animated:NO];

            [_photoTable reloadData];
        }
    }
    else if ([action isEqualToString:[WBUtility postChangedActionUpdate]])
    {
        WBPostItem *updatedItem = [_postChangedNotificationUserInfo objectForKey:[WBUtility postChangedItem]];

        NSMutableArray *array = [NSMutableArray arrayWithArray:_data];
        WBPhotoDisplayItem *displayItem;

        for (int i=0; i<[array count]; i++) {

            displayItem = array[i];
            if ([displayItem.postItem.identifier isEqualToString:[updatedItem identifier]])
            {
                updatedItem.image ? [array replaceObjectAtIndex:i withObject:[WBPhotoDisplayItem itemWithPostItem:updatedItem scaleSize:CGSizeMake([UIScreen mainScreen].bounds.size.width, 250)]] : [array removeObjectAtIndex:i];
                break;
            }
        }
        _data = array;
        [_photoTable reloadData];
    }
    else if ([action isEqualToString:[WBUtility postChangedActionDelete]])
    {
        NSString *deletedItemID = [_postChangedNotificationUserInfo objectForKey:[WBUtility postDeletedItemID]];

        NSMutableArray *array = [NSMutableArray arrayWithArray:_data];
        WBPhotoDisplayItem *displayItem;

        for (int i=0; i<[array count]; i++) {

            displayItem = array[i];
            if ([displayItem.postItem.identifier isEqualToString:deletedItemID])
            {
                [array removeObjectAtIndex:i];
                break;
            }
        }
        _data = array;
        [_photoTable reloadData];
    }
}

#pragma mark - HUD

- (void)showHUD
{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
}

- (void)hideHUD
{
    [MBProgressHUD hideHUDForView:self.view animated:YES];
}

#pragma mark - UITableViewDataSource & UITableViewDelegate

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    return self.data.count;
}

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 250.0f;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    WBPhotoDisplayItem *displayItem = (WBPhotoDisplayItem *)[self.data objectAtIndex:indexPath.row];
    WBPhotoTableCell *cell = [self.photoTable dequeueReusableCellWithIdentifier:PHOTO_CELL];

    // if don't set background color, cell would be blank!!!
    cell.backgroundColor = [UIColor colorWithWhite:0.0 alpha:0.0];

    cell.displayItem = displayItem;
    [cell setNeedsDisplay];
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    WBPhotoDisplayItem *displayItem = [self.data objectAtIndex:indexPath.row];
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    [self toDetail:displayItem.postItem.identifier];
}

#pragma mark - Picture picker

- (void)showImagePickerActionSheet
{
    [_imagePickerActionSheet showInView:self.view];
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    switch (buttonIndex) {
        case 0:
            [self showImagePickerForSourceType:UIImagePickerControllerSourceTypeCamera];
            break;
        case 1:
            [self showImagePickerForSourceType:UIImagePickerControllerSourceTypePhotoLibrary];
            break;
        default:
            break;
    }
}

- (void)showImagePickerForSourceType:(UIImagePickerControllerSourceType)sourceType
{
    _imagePickerController.sourceType = sourceType;

    if (sourceType == UIImagePickerControllerSourceTypeCamera)
    {
        _imagePickerController.showsCameraControls = YES;
    }

    [self presentViewController:_imagePickerController animated:YES completion:nil];
}

- (void)initImagePickerController
{
    if (self.imagePickerController == nil)
    {
        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

            UIImagePickerController *imagePickerController = [[UIImagePickerController alloc] init];
            imagePickerController.modalPresentationStyle = UIModalPresentationCurrentContext;
            imagePickerController.delegate = self;

            dispatch_async(dispatch_get_main_queue(), ^{

                self.imagePickerController = imagePickerController;
                [self.navigationItem.leftBarButtonItem setEnabled:YES];
            });
        });
    }
}

#pragma mark - UIImagePickerControllerDelegate

- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
    UIImage *image = [info valueForKey:UIImagePickerControllerOriginalImage];
    [self dismissViewControllerAnimated:YES completion:NULL];
    [self toPostingWithImage:image];
}
- (void)imagePickerControllerDidCancel:(UIImagePickerController *)picker
{
    [self dismissViewControllerAnimated:YES completion:NULL];
}

#pragma mark - wireframe

- (void)toPostingWithImage:(UIImage *)image
{
    [self.eventHandler toPostingViewWithImage:image];
}

- (void)toDetail:(NSString *)postID
{
    [self.eventHandler toDetailView:postID];
}

@end


text:
package logs

import (
	"fmt"
	"log"
	"os"
	"path"
	"runtime"
	"strconv"
	"strings"
	"sync"
	"time"
)

// RFC5424 logs message levels.
const (
	LevelEmergency = iota
	LevelAlert
	LevelCritical
	LevelError
	LevelWarn
	LevelNotice
	LevelInfo
	LevelDebug
)

// levelLogLogger is defined to implement logs.Logger
// the real logs level will be LevelEmergency
const levelLoggerImpl = -1

// Name for adapter.go
const (
	AdapterConsole   = "console"
	AdapterFile      = "file"
	AdapterMultiFile = "multifile"
	AdapterMail      = "smtp"
	AdapterConn      = "conn"
	AdapterEs        = "es"
	AdapterJianLiao  = "jianliao"
	AdapterSlack     = "slack"
	AdapterAliLS     = "alils"
)

// Legacy logs level constants to ensure backwards compatibility.
const (
	LevelTrace = LevelDebug
)

type newLoggerFunc func() Logger

// Logger defines the behavior of a logs provider.
type Logger interface {
	Init(config string) error
	WriteMsg(when time.Time, msg string, level int) error
	Destroy()
	Flush()
}

var adapters = make(map[string]newLoggerFunc)
var levelPrefix = [LevelDebug + 1]string{"[M] ", "[A] ", "[C] ", "[E] ", "[W] ", "[N] ", "[I] ", "[D] "}

func ParseLevel(lvl string) (int, error) {
	switch strings.ToLower(lvl) {
	case "emergency":
		return LevelEmergency, nil
	case "critical":
		return LevelCritical, nil
	case "alert":
		return LevelAlert, nil
	case "notice":
		return LevelNotice, nil
	case "error":
		return LevelError, nil
	case "warn":
		return LevelWarn, nil
	case "info":
		return LevelInfo, nil
	case "debug":
		return LevelDebug, nil
	}

	var l int
	return l, fmt.Errorf("not a valid Level: %q", lvl)
}

// Register makes a logs provide available by the provided name.
// If Register is called twice with the same name or if driver is nil,
// it panics.
func Register(name string, log newLoggerFunc) {
	if log == nil {
		panic("logs: Register provide is nil")
	}
	if _, dup := adapters[name]; dup {
		panic("logs: Register called twice for provider " + name)
	}
	adapters[name] = log
}

type DefaultLogger struct {
	lock                sync.Mutex
	level               int
	init                bool
	enableFuncCallDepth bool
	loggerFuncCallDepth int
	asynchronous        bool
	msgChanLen          int64
	msgChan             chan *logMsg
	signalChan          chan string
	wg                  sync.WaitGroup
	outputs             []*nameLogger
}

const defaultAsyncMsgLen = 1e3

type nameLogger struct {
	Logger
	name string
}

type logMsg struct {
	level int
	msg   string
	when  time.Time
}

var logMsgPool *sync.Pool

// NewLogger returns a new Logger.
// channelLen means the number of messages in chan(used where asynchronous is true).
// if the buffering chan is full, logger adapters write to file or other way.
func NewLogger(channelLens ...int64) *DefaultLogger {
	dl := new(DefaultLogger)
	dl.level = LevelDebug
	dl.loggerFuncCallDepth = 2
	dl.msgChanLen = append(channelLens, 0)[0]
	if dl.msgChanLen <= 0 {
		dl.msgChanLen = defaultAsyncMsgLen
	}
	dl.signalChan = make(chan string, 1)
	dl.setLogger(AdapterConsole)
	return dl
}

// Async set the logs to asynchronous and start the goroutine
func (dl *DefaultLogger) Async(msgLen ...int64) *DefaultLogger {
	dl.lock.Lock()
	defer dl.lock.Unlock()
	if dl.asynchronous {
		return dl
	}
	dl.asynchronous = true
	if len(msgLen) > 0 && msgLen[0] > 0 {
		dl.msgChanLen = msgLen[0]
	}
	dl.msgChan = make(chan *logMsg, dl.msgChanLen)
	logMsgPool = &sync.Pool{
		New: func() interface{} {
			return &logMsg{}
		},
	}
	dl.wg.Add(1)
	go dl.startLogger()
	return dl
}

// SetLogger provides a given logger adapter.go into Logger with config string.
// config need to be correct JSON as string: {"interval":360}.
func (dl *DefaultLogger) setLogger(adapterName string, configs ...string) error {
	config := append(configs, "{}")[0]
	for _, l := range dl.outputs {
		if l.name == adapterName {
			return fmt.Errorf("logs: duplicate adaptername %q (you have set this logger before)", adapterName)
		}
	}

	log, ok := adapters[adapterName]
	if !ok {
		return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adapterName)
	}

	lg := log()
	err := lg.Init(config)
	if err != nil {
		fmt.Fprintln(os.Stderr, "logs.Logger.SetLogger: "+err.Error())
		return err
	}
	dl.outputs = append(dl.outputs, &nameLogger{name: adapterName, Logger: lg})
	return nil
}

// SetLogger provides a given logger adapter.go into Logger with config string.
// config need to be correct JSON as string: {"interval":360}.
func (dl *DefaultLogger) SetLogger(adapterName string, configs ...string) error {
	dl.lock.Lock()
	defer dl.lock.Unlock()
	if !dl.init {
		dl.outputs = []*nameLogger{}
		dl.init = true
	}
	return dl.setLogger(adapterName, configs...)
}

// DelLogger remove a logger adapter.go in Logger.
func (dl *DefaultLogger) DelLogger(adapterName string) error {
	dl.lock.Lock()
	defer dl.lock.Unlock()
	outputs := []*nameLogger{}
	for _, lg := range dl.outputs {
		if lg.name == adapterName {
			lg.Destroy()
		} else {
			outputs = append(outputs, lg)
		}
	}
	if len(outputs) == len(dl.outputs) {
		return fmt.Errorf("logs: unknown adaptername %q (forgotten Register?)", adapterName)
	}
	dl.outputs = outputs
	return nil
}

func (dl *DefaultLogger) writeToLoggers(when time.Time, msg string, level int) {
	for _, l := range dl.outputs {
		err := l.WriteMsg(when, msg, level)
		if err != nil {
			fmt.Fprintf(os.Stderr, "unable to WriteMsg to adapter.go:%v,error:%v\n", l.name, err)
		}
	}
}

func (dl *DefaultLogger) Write(p []byte) (n int, err error) {
	if len(p) == 0 {
		return 0, nil
	}
	// writeMsg will always add a '\n' character
	if p[len(p)-1] == '\n' {
		p = p[0 : len(p)-1]
	}
	// set levelLoggerImpl to ensure all logs message will be write out
	err = dl.writeMsg(levelLoggerImpl, string(p))
	if err == nil {
		return len(p), err
	}
	return 0, err
}

func (dl *DefaultLogger) writeMsg(logLevel int, msg string, v ...interface{}) error {
	if !dl.init {
		dl.lock.Lock()
		dl.setLogger(AdapterConsole)
		dl.lock.Unlock()
	}

	if len(v) > 0 {
		msg = fmt.Sprintf(msg, v...)
	}
	when := time.Now()
	if dl.enableFuncCallDepth {
		_, file, line, ok := runtime.Caller(dl.loggerFuncCallDepth)
		if !ok {
			file = "???"
			line = 0
		}
		_, filename := path.Split(file)
		msg = "[" + filename + ":" + strconv.Itoa(line) + "] " + msg
	}

	//set level info in front of filename info
	if logLevel == levelLoggerImpl {
		// set to emergency to ensure all logs will be print out correctly
		logLevel = LevelEmergency
	} else {
		msg = levelPrefix[logLevel] + msg
	}

	if dl.asynchronous {
		lm := logMsgPool.Get().(*logMsg)
		lm.level = logLevel
		lm.msg = msg
		lm.when = when
		dl.msgChan <- lm
	} else {
		dl.writeToLoggers(when, msg, logLevel)
	}
	return nil
}

// SetLevel Set logs message level.
// If message level (such as LevelDebug) is higher than logger level (such as LevelWarning),
// logs providers will not even be sent the message.
func (dl *DefaultLogger) SetLevel(l int) {
	dl.level = l
}

// SetLogFuncCallDepth set logs funcCallDepth
func (dl *DefaultLogger) SetLogFuncCallDepth(d int) {
	dl.loggerFuncCallDepth = d
}

// GetLogFuncCallDepth return logs funcCallDepth for wrapper
func (dl *DefaultLogger) GetLogFuncCallDepth() int {
	return dl.loggerFuncCallDepth
}

// EnableFuncCallDepth enable logs funcCallDepth
func (dl *DefaultLogger) EnableFuncCallDepth(b bool) {
	dl.enableFuncCallDepth = b
}

// start logger chan reading.
// when chan is not empty, write logs.
func (dl *DefaultLogger) startLogger() {
	gameOver := false
	for {
		select {
		case bm := <-dl.msgChan:
			dl.writeToLoggers(bm.when, bm.msg, bm.level)
			logMsgPool.Put(bm)
		case sg := <-dl.signalChan:
			// Now should only send "flush" or "close" to dl.signalChan
			dl.flush()
			if sg == "close" {
				for _, l := range dl.outputs {
					l.Destroy()
				}
				dl.outputs = nil
				gameOver = true
			}
			dl.wg.Done()
		}
		if gameOver {
			break
		}
	}
}

// Emergency Log EMERGENCY level message.
func (dl *DefaultLogger) Emergency(format string, v ...interface{}) {
	if LevelEmergency > dl.level {
		return
	}
	dl.writeMsg(LevelEmergency, format, v...)
}

// Alert Log ALERT level message.
func (dl *DefaultLogger) Alert(format string, v ...interface{}) {
	if LevelAlert > dl.level {
		return
	}
	dl.writeMsg(LevelAlert, format, v...)
}

// Critical Log CRITICAL level message.
func (dl *DefaultLogger) Critical(format string, v ...interface{}) {
	if LevelCritical > dl.level {
		return
	}
	dl.writeMsg(LevelCritical, format, v...)
}

func (dl *DefaultLogger) Error(format string, v ...interface{}) {
	if LevelError > dl.level {
		return
	}
	dl.writeMsg(LevelError, format, v...)
}

func (dl *DefaultLogger) Notice(format string, v ...interface{}) {
	if LevelNotice > dl.level {
		return
	}
	dl.writeMsg(LevelNotice, format, v...)
}

func (dl *DefaultLogger) Info(format string, v ...interface{}) {
	if LevelInfo > dl.level {
		return
	}
	dl.writeMsg(LevelInfo, format, v...)
}

func (dl *DefaultLogger) Debug(format string, v ...interface{}) {
	if LevelDebug > dl.level {
		return
	}
	dl.writeMsg(LevelDebug, format, v...)
}

func (dl *DefaultLogger) Warn(format string, v ...interface{}) {
	if LevelWarn > dl.level {
		return
	}
	dl.writeMsg(LevelWarn, format, v...)
}

// Trace Log TRACE level message.
// compatibility alias for Debug()
func (dl *DefaultLogger) Trace(format string, v ...interface{}) {
	if LevelDebug > dl.level {
		return
	}
	dl.writeMsg(LevelDebug, format, v...)
}

// Flush flush all chan data.
func (dl *DefaultLogger) Flush() {
	if dl.asynchronous {
		dl.signalChan <- "flush"
		dl.wg.Wait()
		dl.wg.Add(1)
		return
	}
	dl.flush()
}

// Close close logger, flush all chan data and destroy all adapters in Logger.
func (dl *DefaultLogger) Close() {
	if dl.asynchronous {
		dl.signalChan <- "close"
		dl.wg.Wait()
		close(dl.msgChan)
	} else {
		dl.flush()
		for _, l := range dl.outputs {
			l.Destroy()
		}
		dl.outputs = nil
	}
	close(dl.signalChan)
}

// Reset close all outputs, and set dl.outputs to nil
func (dl *DefaultLogger) Reset() {
	dl.Flush()
	for _, l := range dl.outputs {
		l.Destroy()
	}
	dl.outputs = nil
}

func (dl *DefaultLogger) flush() {
	if dl.asynchronous {
		for {
			if len(dl.msgChan) > 0 {
				bm := <-dl.msgChan
				dl.writeToLoggers(bm.when, bm.msg, bm.level)
				logMsgPool.Put(bm)
				continue
			}
			break
		}
	}
	for _, l := range dl.outputs {
		l.Flush()
	}
}

// defaultLogger references the used application logger.
var defaultLogger = NewLogger()

// GetDefaultLogger returns the default Logger
func GetDefaultLogger() *DefaultLogger {
	return defaultLogger
}

var loggerMap = struct {
	sync.RWMutex
	logs map[string]*log.Logger
}{
	logs: map[string]*log.Logger{},
}

// GetLogger returns the default Logger
func GetLogger(prefixes ...string) *log.Logger {
	prefix := append(prefixes, "")[0]
	if prefix != "" {
		prefix = fmt.Sprintf(`[%s] `, strings.ToUpper(prefix))
	}
	loggerMap.RLock()
	l, ok := loggerMap.logs[prefix]
	if ok {
		loggerMap.RUnlock()
		return l
	}
	loggerMap.RUnlock()
	loggerMap.Lock()
	defer loggerMap.Unlock()
	l, ok = loggerMap.logs[prefix]
	if !ok {
		l = log.New(defaultLogger, prefix, 0)
		loggerMap.logs[prefix] = l
	}
	return l
}

// Reset will remove all the adapter.go
func Reset() {
	defaultLogger.Reset()
}

// Async set the Default with Async mode and hold msglen messages
func Async(msgLen ...int64) *DefaultLogger {
	return defaultLogger.Async(msgLen...)
}

// SetLevel sets the global logs level used by the simple logger.
func SetLevel(l int) {
	defaultLogger.SetLevel(l)
}

// EnableFuncCallDepth enable logs funcCallDepth
func EnableFuncCallDepth(b bool) {
	defaultLogger.enableFuncCallDepth = b
}

// SetLogFuncCall set the CallDepth, default is 4
func SetLogFuncCall(b bool) {
	defaultLogger.EnableFuncCallDepth(b)
	defaultLogger.SetLogFuncCallDepth(4)
}

// SetLogFuncCallDepth set logs funcCallDepth
func SetLogFuncCallDepth(d int) {
	defaultLogger.loggerFuncCallDepth = d
}

// SetLogger sets a new logger.
func SetLogger(adapter string, config ...string) error {
	return defaultLogger.SetLogger(adapter, config...)
}

// Emergency logs a message at emergency level.
func Emergency(f interface{}, v ...interface{}) {
	defaultLogger.Emergency(formatLog(f, v...))
}

// Alert logs a message at alert level.
func Alert(f interface{}, v ...interface{}) {
	defaultLogger.Alert(formatLog(f, v...))
}

// Critical logs a message at critical level.
func Critical(f interface{}, v ...interface{}) {
	defaultLogger.Critical(formatLog(f, v...))
}

// Error logs a message at error level.
func Error(f interface{}, v ...interface{}) {
	defaultLogger.Error(formatLog(f, v...))
}

// Warn compatibility alias for Warning()
func Warn(f interface{}, v ...interface{}) {
	defaultLogger.Warn(formatLog(f, v...))
}

// Notice logs a message at notice level.
func Notice(f interface{}, v ...interface{}) {
	defaultLogger.Notice(formatLog(f, v...))
}

// Info compatibility alias for Warning()
func Info(f interface{}, v ...interface{}) {
	defaultLogger.Info(formatLog(f, v...))
}

// Debug logs a message at debug level.
func Debug(f interface{}, v ...interface{}) {
	defaultLogger.Debug(formatLog(f, v...))
}

// Trace logs a message at trace level.
// compatibility alias for Warning()
func Trace(f interface{}, v ...interface{}) {
	defaultLogger.Trace(formatLog(f, v...))
}

func formatLog(f interface{}, v ...interface{}) string {
	var msg string
	switch f.(type) {
	case string:
		msg = f.(string)
		if len(v) == 0 {
			return msg
		}
		if strings.Contains(msg, "%") && !strings.Contains(msg, "%%") {
			//format string
		} else {
			//do not contain format char
			msg += strings.Repeat(" %v", len(v))
		}
	default:
		msg = fmt.Sprint(f)
		if len(v) == 0 {
			return msg
		}
		msg += strings.Repeat(" %v", len(v))
	}
	return fmt.Sprintf(msg, v...)
}


text:
package org.wickedsource.coderadar.analyzer.todo;

import org.wickedsource.coderadar.analyzer.api.*;

import java.io.IOException;
import java.util.Arrays;
import java.util.List;

public class TodoSourceCodeFileAnalyzerPlugin implements SourceCodeFileAnalyzerPlugin {

    public static final Metric TODO_METRIC = new Metric("org.wickedsource.coderadar.analyzer.todo.TodoAnalyzer.todo");

    private String patternPropertyPrefix = TodoSourceCodeFileAnalyzerPlugin.class.getName() + ".pattern";

    private TodoFinder todoFinder;

    private List<String> getDefaultPatterns() {
        return Arrays.asList("TODO", "FIXME", "todo", "fixme");
    }

    @Override
    public AnalyzerFileFilter getFilter() {
        return new DefaultFileFilter();
    }

    @Override
    public FileMetrics analyzeFile(String filename, byte[] fileContent) throws AnalyzerException {
        try {
            List<Finding> findings = todoFinder.findTodos(fileContent);
            FileMetrics metrics = new FileMetrics();
            metrics.addFindings(TODO_METRIC, findings);
            metrics.setMetricCount(TODO_METRIC, (long) findings.size());
            return metrics;
        } catch (IOException e) {
            throw new AnalyzerException(e);
        }
    }

}


text:
"""
    Pygments
    ~~~~~~~~

    Pygments is a syntax highlighting package written in Python.

    It is a generic syntax highlighter for general use in all kinds of software
    such as forum systems, wikis or other applications that need to prettify
    source code. Highlights are:

    * a wide range of common languages and markup formats is supported
    * special attention is paid to details, increasing quality by a fair amount
    * support for new languages and formats are added easily
    * a number of output formats, presently HTML, LaTeX, RTF, SVG, all image
      formats that PIL supports, and ANSI sequences
    * it is usable as a command-line tool and as a library
    * ... and it highlights even Brainfuck!

    The `Pygments tip`_ is installable with ``easy_install Pygments==dev``.

    .. _Pygments tip:
       http://bitbucket.org/birkenfeld/pygments-main/get/tip.zip#egg=Pygments-dev

    :copyright: Copyright 2006-2011 by the Pygments team, see AUTHORS.
    :license: BSD, see LICENSE for details.
"""

__version__ = '1.4'
__docformat__ = 'restructuredtext'

__all__ = ['lex', 'format', 'highlight']

import sys

from pygments.util import StringIO, BytesIO

def lex(code, lexer):
    """
    Lex ``code`` with ``lexer`` and return an iterable of tokens.
    """
    try:
        return lexer.get_tokens(code)
    except TypeError, err:
        if isinstance(err.args[0], str) and \
           'unbound method get_tokens' in err.args[0]:
            raise TypeError('lex() argument must be a lexer instance, '
                            'not a class')
        raise

def format(tokens, formatter, outfile=None):
    """
    Format a tokenlist ``tokens`` with the formatter ``formatter``.

    If ``outfile`` is given and a valid file object (an object
    with a ``write`` method), the result will be written to it, otherwise
    it is returned as a string.
    """
    try:
        if not outfile:
            #print formatter, 'using', formatter.encoding
            realoutfile = formatter.encoding and BytesIO() or StringIO()
            formatter.format(tokens, realoutfile)
            return realoutfile.getvalue()
        else:
            formatter.format(tokens, outfile)
    except TypeError, err:
        if isinstance(err.args[0], str) and \
           'unbound method format' in err.args[0]:
            raise TypeError('format() argument must be a formatter instance, '
                            'not a class')
        raise

def highlight(code, lexer, formatter, outfile=None):
    """
    Lex ``code`` with ``lexer`` and format it with the formatter ``formatter``.

    If ``outfile`` is given and a valid file object (an object
    with a ``write`` method), the result will be written to it, otherwise
    it is returned as a string.
    """
    return format(lex(code, lexer), formatter, outfile)

if __name__ == '__main__':
    from pygments.cmdline import main
    sys.exit(main(sys.argv))


text:
package io.probedock.demo.itf.service;

import io.probedock.jee.itf.TestGroup;

import javax.ejb.Local;

/**
 * @author Laurent Prevost <laurent.prevost@probedock.io>
 */
@Local
public interface CalculatorServiceTest extends TestGroup {
}


text:
<!DOCTYPE html>
<html lang="en">

  <head>

    @include('partials._head')

  </head>

  <body>

    <!-- NAVBAR DE BOOTSTRAP POR DEFAULT -->
    @include('partials._nav')

    <div class="container">

      @include('partials._mensajes')

      @yield('contenido')

      @include('partials._footer')

    </div> <!-- FIN DEL CONTENEDOR -->

    @include('partials._javascripts')

    @yield('scripts')

  </body>
</html>


text:
package com.varunsdave.ctci_01_01;

import java.io.*;
import java.util.*;
import java.lang.*;

/**
 *  @author Varun Dave
 *  @version 0.1
 *
 *  This code provides solution to a problem that asks to determine
 *  whether a given string contains only unique chars.
 *
 *  The space requirement for this solution is n for the length 128
 *  The code is tested for ASCII character set only.
 *
 *  This code is case-sensitive. That is, it treats a and A as two different
 *  characters.
 *
 */
public class Solution {

	public static void main(String[] args) throws java.lang.Exception{
		String pass_test = "sample";
		String fail_test = "sample text"; //should fail at double t

		System.out.println("the result from pass_test is : " + containsUniqueChars(pass_test));
		System.out.println("the result from fail_test is : "+ containsUniqueChars(fail_test));

	}

	private static boolean containsUniqueChars(String input_string){
		if (input_string.length()>128){
			return false;
		}

		int [] char_occurences = new int [256];

		for (int i = 0; i< input_string.length(); i++){
			int val = input_string.charAt(i);
			char_occurences[val]++;
			if (char_occurences[val] > 1){

				return false;
			}
		}
		return true;
	}

}


text:
title: aws_dynamodb
type: output
status: stable
categories: ["Services","AWS"]
---

<!--
     THIS FILE IS AUTOGENERATED!

     To make changes please edit the contents of:
     lib/output/aws_dynamodb.go
-->

import Tabs from '@theme/Tabs';
import TabItem from '@theme/TabItem';

Inserts items into a DynamoDB table.

Introduced in version 3.36.0.

<Tabs defaultValue="common" values={[
  { label: 'Common', value: 'common', },
  { label: 'Advanced', value: 'advanced', },
]}>

<TabItem value="common">

```yml
# Common config fields, showing default values
output:
  label: ""
  aws_dynamodb:
    table: ""
    string_columns: {}
    json_map_columns: {}
    max_in_flight: 1
    batching:
      count: 0
      byte_size: 0
      period: ""
      check: ""
```

</TabItem>
<TabItem value="advanced">

```yml
# All config fields, showing default values
output:
  label: ""
  aws_dynamodb:
    table: ""
    string_columns: {}
    json_map_columns: {}
    ttl: ""
    ttl_key: ""
    max_in_flight: 1
    batching:
      count: 0
      byte_size: 0
      period: ""
      check: ""
      processors: []
    region: ""
    endpoint: ""
    credentials:
      profile: ""
      id: ""
      secret: ""
      token: ""
      role: ""
      role_external_id: ""
    max_retries: 3
    backoff:
      initial_interval: 1s
      max_interval: 5s
      max_elapsed_time: 30s
```

</TabItem>
</Tabs>

The field `string_columns` is a map of column names to string values,
where the values are
[function interpolated](/docs/configuration/interpolation#bloblang-queries) per message of a
batch. This allows you to populate string columns of an item by extracting
fields within the document payload or metadata like follows:

```yml
string_columns:
  id: ${!json("id")}
  title: ${!json("body.title")}
  topic: ${!meta("kafka_topic")}
  full_content: ${!content()}
```

The field `json_map_columns` is a map of column names to json paths,
where the [dot path](/docs/configuration/field_paths) is extracted from each document and
converted into a map value. Both an empty path and the path `.` are
interpreted as the root of the document. This allows you to populate map columns
of an item like follows:

```yml
json_map_columns:
  user: path.to.user
  whole_document: .
```

A column name can be empty:

```yml
json_map_columns:
  "": .
```

In which case the top level document fields will be written at the root of the
item, potentially overwriting previously defined column values. If a path is not
found within a document the column will not be populated.

### Credentials

By default Benthos will use a shared credentials file when connecting to AWS
services. It's also possible to set them explicitly at the component level,
allowing you to transfer data across accounts. You can find out more
[in this document](/docs/guides/cloud/aws).

## Performance

This output benefits from sending multiple messages in flight in parallel for
improved performance. You can tune the max number of in flight messages with the
field `max_in_flight`.

This output benefits from sending messages as a batch for improved performance.
Batches can be formed at both the input and output level. You can find out more
[in this doc](/docs/configuration/batching).

## Fields

### `table`

The table to store messages in.

Type: `string`
Default: `""`

### `string_columns`

A map of column keys to string values to store.
This field supports [interpolation functions](/docs/configuration/interpolation#bloblang-queries).

Type: `object`
Default: `{}`

```yml
# Examples

string_columns:
  full_content: ${!content()}
  id: ${!json("id")}
  title: ${!json("body.title")}
  topic: ${!meta("kafka_topic")}
```

### `json_map_columns`

A map of column keys to [field paths](/docs/configuration/field_paths) pointing to value data within messages.

Type: `object`
Default: `{}`

```yml
# Examples

json_map_columns:
  user: path.to.user
  whole_document: .

json_map_columns:
  "": .
```

### `ttl`

An optional TTL to set for items, calculated from the moment the message is sent.

Type: `string`
Default: `""`

### `ttl_key`

The column key to place the TTL value within.

Type: `string`
Default: `""`

### `max_in_flight`

The maximum number of messages to have in flight at a given time. Increase this to improve throughput.

Type: `int`
Default: `1`

### `batching`

Allows you to configure a [batching policy](/docs/configuration/batching).

Type: `object`

```yml
# Examples

batching:
  byte_size: 5000
  count: 0
  period: 1s

batching:
  count: 10
  period: 1s

batching:
  check: this.contains("END BATCH")
  count: 0
  period: 1m
```

### `batching.count`

A number of messages at which the batch should be flushed. If `0` disables count based batching.

Type: `int`
Default: `0`

### `batching.byte_size`

An amount of bytes at which the batch should be flushed. If `0` disables size based batching.

Type: `int`
Default: `0`

### `batching.period`

A period in which an incomplete batch should be flushed regardless of its size.

Type: `string`
Default: `""`

```yml
# Examples

period: 1s

period: 1m

period: 500ms
```

### `batching.check`

A [Bloblang query](/docs/guides/bloblang/about/) that should return a boolean value indicating whether a message should end a batch.

Type: `string`
Default: `""`

```yml
# Examples

check: this.type == "end_of_transaction"
```

### `batching.processors`

A list of [processors](/docs/components/processors/about) to apply to a batch as it is flushed. This allows you to aggregate and archive the batch however you see fit. Please note that all resulting messages are flushed as a single batch, therefore splitting the batch into smaller batches using these processors is a no-op.

Type: `array`
Default: `[]`

```yml
# Examples

processors:
  - archive:
      format: lines

processors:
  - archive:
      format: json_array

processors:
  - merge_json: {}
```

### `region`

The AWS region to target.

Type: `string`
Default: `""`

### `endpoint`

Allows you to specify a custom endpoint for the AWS API.

Type: `string`
Default: `""`

### `credentials`

Optional manual configuration of AWS credentials to use. More information can be found [in this document](/docs/guides/cloud/aws).

Type: `object`

### `credentials.profile`

A profile from `~/.aws/credentials` to use.

Type: `string`
Default: `""`

### `credentials.id`

The ID of credentials to use.

Type: `string`
Default: `""`

### `credentials.secret`

The secret for the credentials being used.

Type: `string`
Default: `""`

### `credentials.token`

The token for the credentials being used, required when using short term credentials.

Type: `string`
Default: `""`

### `credentials.role`

A role ARN to assume.

Type: `string`
Default: `""`

### `credentials.role_external_id`

An external ID to provide when assuming a role.

Type: `string`
Default: `""`

### `max_retries`

The maximum number of retries before giving up on the request. If set to zero there is no discrete limit.

Type: `int`
Default: `3`

### `backoff`

Control time intervals between retry attempts.

Type: `object`

### `backoff.initial_interval`

The initial period to wait between retry attempts.

Type: `string`
Default: `"1s"`

### `backoff.max_interval`

The maximum period to wait between retry attempts.

Type: `string`
Default: `"5s"`

### `backoff.max_elapsed_time`

The maximum period to wait before retry attempts are abandoned. If zero then no limit is used.

Type: `string`
Default: `"30s"`


text:
#include "net/third_party/quic/core/http/http_framer.h"
#include "net/third_party/quic/platform/api/quic_arraysize.h"
#include "net/third_party/quic/platform/api/quic_test.h"

using testing::InSequence;

namespace quic {

class MockVisitor : public HttpFramer::Visitor {
 public:
  virtual ~MockVisitor() = default;

  // Called if an error is detected.
  MOCK_METHOD1(OnError, void(HttpFramer* framer));

  MOCK_METHOD1(OnPriorityFrame, void(const PriorityFrame& frame));
  MOCK_METHOD1(OnCancelPushFrame, void(const CancelPushFrame& frame));
  MOCK_METHOD1(OnMaxPushIdFrame, void(const MaxPushIdFrame& frame));
  MOCK_METHOD1(OnGoAwayFrame, void(const GoAwayFrame& frame));
  MOCK_METHOD1(OnSettingsFrame, void(const SettingsFrame& frame));

  MOCK_METHOD0(OnDataFrameStart, void());
  MOCK_METHOD1(OnDataFramePayload, void(QuicStringPiece payload));
  MOCK_METHOD0(OnDataFrameEnd, void());

  MOCK_METHOD0(OnHeadersFrameStart, void());
  MOCK_METHOD1(OnHeadersFramePayload, void(QuicStringPiece payload));
  MOCK_METHOD0(OnHeadersFrameEnd, void());

  MOCK_METHOD1(OnPushPromiseFrameStart, void(PushId push_id));
  MOCK_METHOD1(OnPushPromiseFramePayload, void(QuicStringPiece payload));
  MOCK_METHOD0(OnPushPromiseFrameEnd, void());
};

class HttpFramerTest : public QuicTest {
 public:
  HttpFramerTest() { framer_.set_visitor(&visitor_); }
  HttpFramer framer_;
  testing::StrictMock<MockVisitor> visitor_;
};

TEST_F(HttpFramerTest, InitialState) {
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());
}

TEST_F(HttpFramerTest, ReservedFramesNoPayload) {
  for (int n = 0; n < 8; ++n) {
    const uint8_t type = 0xB + 0x1F * n;
    char input[] = {// length
                    0x00,
                    // type
                    type};

    EXPECT_EQ(2u, framer_.ProcessInput(input, QUIC_ARRAYSIZE(input))) << n;
    EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
    ASSERT_EQ("", framer_.error_detail());
  }
}

TEST_F(HttpFramerTest, ReservedFramesSmallPayload) {
  for (int n = 0; n < 8; ++n) {
    const uint8_t type = 0xB + 0x1F * n;
    const uint8_t payload_size = 50;
    char input[payload_size + 2] = {// length
                                    payload_size,
                                    // type
                                    type};

    EXPECT_EQ(QUIC_ARRAYSIZE(input),
              framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)))
        << n;
    EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
    ASSERT_EQ("", framer_.error_detail());
  }
}

TEST_F(HttpFramerTest, ReservedFramesLargePayload) {
  for (int n = 0; n < 8; ++n) {
    const uint8_t type = 0xB + 0x1F * n;
    const size_t payload_size = 256;
    char input[payload_size + 3] = {// length
                                    0x40 + 0x01, 0x00,
                                    // type
                                    type};

    EXPECT_EQ(QUIC_ARRAYSIZE(input),
              framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)))
        << n;
    EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
    ASSERT_EQ("", framer_.error_detail());
  }
}

TEST_F(HttpFramerTest, CancelPush) {
  char input[] = {// length
                  0x2,
                  // type (CANCEL_PUSH)
                  0x03,
                  // Push Id
                  0x01};

  // Process the full frame.
  EXPECT_CALL(visitor_, OnCancelPushFrame(CancelPushFrame({1})));
  EXPECT_EQ(QUIC_ARRAYSIZE(input),
            framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)));
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());

  // Process the frame incremently.
  EXPECT_CALL(visitor_, OnCancelPushFrame(CancelPushFrame({1})));
  for (char c : input) {
    EXPECT_EQ(1u, framer_.ProcessInput(&c, 1));
  }
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());
}

TEST_F(HttpFramerTest, PushPromiseFrame) {
  char input[] = {// length
                  0x8,
                  // type (PUSH_PROMISE)
                  0x05,
                  // Push Id
                  0x01,
                  // Header Block
                  'H', 'e', 'a', 'd', 'e', 'r', 's'};

  // Process the full frame.
  InSequence s;
  EXPECT_CALL(visitor_, OnPushPromiseFrameStart(1));
  EXPECT_CALL(visitor_, OnPushPromiseFramePayload("Headers"));
  EXPECT_CALL(visitor_, OnPushPromiseFrameEnd());
  EXPECT_EQ(QUIC_ARRAYSIZE(input),
            framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)));
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());

  // Process the frame incremently.
  EXPECT_CALL(visitor_, OnPushPromiseFrameStart(1));
  EXPECT_CALL(visitor_, OnPushPromiseFramePayload("H"));
  EXPECT_CALL(visitor_, OnPushPromiseFramePayload("e"));
  EXPECT_CALL(visitor_, OnPushPromiseFramePayload("a"));
  EXPECT_CALL(visitor_, OnPushPromiseFramePayload("d"));
  EXPECT_CALL(visitor_, OnPushPromiseFramePayload("e"));
  EXPECT_CALL(visitor_, OnPushPromiseFramePayload("r"));
  EXPECT_CALL(visitor_, OnPushPromiseFramePayload("s"));
  EXPECT_CALL(visitor_, OnPushPromiseFrameEnd());
  for (char c : input) {
    EXPECT_EQ(1u, framer_.ProcessInput(&c, 1));
  }
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());
}

TEST_F(HttpFramerTest, MaxPushId) {
  char input[] = {// length
                  0x2,
                  // type (MAX_PUSH_ID)
                  0x0D,
                  // Push Id
                  0x01};

  // Process the full frame.
  EXPECT_CALL(visitor_, OnMaxPushIdFrame(MaxPushIdFrame({1})));
  EXPECT_EQ(QUIC_ARRAYSIZE(input),
            framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)));
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());

  // Process the frame incremently.
  EXPECT_CALL(visitor_, OnMaxPushIdFrame(MaxPushIdFrame({1})));
  for (char c : input) {
    EXPECT_EQ(1u, framer_.ProcessInput(&c, 1));
  }
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());
}

TEST_F(HttpFramerTest, PriorityFrame) {
  char input[] = {// length
                  0x4,
                  // type (PRIORITY)
                  0x2,
                  // request stream, request stream, exclusive
                  0x01,
                  // prioritized_element_id
                  0x03,
                  // element_dependency_id
                  0x04,
                  // weight
                  0xFF};

  PriorityFrame frame;
  frame.prioritized_type = REQUEST_STREAM;
  frame.dependency_type = REQUEST_STREAM;
  frame.exclusive = true;
  frame.prioritized_element_id = 0x03;
  frame.element_dependency_id = 0x04;
  frame.weight = 0xFF;

  // Process the full frame.
  EXPECT_CALL(visitor_, OnPriorityFrame(frame));
  EXPECT_EQ(QUIC_ARRAYSIZE(input),
            framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)));
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());

  /*
  // Process the frame incremently.
  EXPECT_CALL(visitor_, OnPriorityFrame(frame));
  for (char c : input) {
    EXPECT_EQ(1u, framer_.ProcessInput(&c, 1));
  }
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());
  */
}

TEST_F(HttpFramerTest, SettingsFrame) {
  char input[] = {
      // length
      0x17,
      // type (SETTINGS)
      0x04,
      // identifier (SETTINGS_NUM_PLACEHOLDERS)
      0x00, 0x03,
      // length
      0x02,
      // content
      0x00, 0x02,
      // identifier (SETTINGS_MAX_HEADER_LIST_SIZE)
      0x00, 0x06,
      // length
      0x04,
      // content
      0x00, 0x00, 0x00, 0x05,
      // identifier (unknown)
      0x00, 0x05,
      // length
      0x08,
      // content
      0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07,
  };

  SettingsFrame frame;
  frame.values[3] = 2;
  frame.values[6] = 5;

  // Process the full frame.
  EXPECT_CALL(visitor_, OnSettingsFrame(frame));
  EXPECT_EQ(QUIC_ARRAYSIZE(input),
            framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)));
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());

  // Process the frame incremently.
  EXPECT_CALL(visitor_, OnSettingsFrame(frame));
  for (char c : input) {
    EXPECT_EQ(1u, framer_.ProcessInput(&c, 1));
  }
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());
}

TEST_F(HttpFramerTest, DataFrame) {
  char input[] = {// length
                  0x05,
                  // type (DATA)
                  0x00,
                  // data
                  'D', 'a', 't', 'a', '!'};

  // Process the full frame.
  InSequence s;
  EXPECT_CALL(visitor_, OnDataFrameStart());
  EXPECT_CALL(visitor_, OnDataFramePayload("Data!"));
  EXPECT_CALL(visitor_, OnDataFrameEnd());
  EXPECT_EQ(QUIC_ARRAYSIZE(input),
            framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)));
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());

  // Process the frame incremently.
  EXPECT_CALL(visitor_, OnDataFrameStart());
  EXPECT_CALL(visitor_, OnDataFramePayload("D"));
  EXPECT_CALL(visitor_, OnDataFramePayload("a"));
  EXPECT_CALL(visitor_, OnDataFramePayload("t"));
  EXPECT_CALL(visitor_, OnDataFramePayload("a"));
  EXPECT_CALL(visitor_, OnDataFramePayload("!"));
  EXPECT_CALL(visitor_, OnDataFrameEnd());
  for (char c : input) {
    EXPECT_EQ(1u, framer_.ProcessInput(&c, 1));
  }
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());
}

TEST_F(HttpFramerTest, GoAway) {
  char input[] = {// length
                  0x1,
                  // type (GOAWAY)
                  0x07,
                  // StreamId
                  0x01};

  // Process the full frame.
  EXPECT_CALL(visitor_, OnGoAwayFrame(GoAwayFrame({1})));
  EXPECT_EQ(QUIC_ARRAYSIZE(input),
            framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)));
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());

  // Process the frame incremently.
  EXPECT_CALL(visitor_, OnGoAwayFrame(GoAwayFrame({1})));
  for (char c : input) {
    EXPECT_EQ(1u, framer_.ProcessInput(&c, 1));
  }
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());
}

TEST_F(HttpFramerTest, HeadersFrame) {
  char input[] = {// length
                  0x07,
                  // type (HEADERS)
                  0x01,
                  // headers
                  'H', 'e', 'a', 'd', 'e', 'r', 's'};

  // Process the full frame.
  InSequence s;
  EXPECT_CALL(visitor_, OnHeadersFrameStart());
  EXPECT_CALL(visitor_, OnHeadersFramePayload("Headers"));
  EXPECT_CALL(visitor_, OnHeadersFrameEnd());
  EXPECT_EQ(QUIC_ARRAYSIZE(input),
            framer_.ProcessInput(input, QUIC_ARRAYSIZE(input)));
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());

  // Process the frame incremently.
  EXPECT_CALL(visitor_, OnHeadersFrameStart());
  EXPECT_CALL(visitor_, OnHeadersFramePayload("H"));
  EXPECT_CALL(visitor_, OnHeadersFramePayload("e"));
  EXPECT_CALL(visitor_, OnHeadersFramePayload("a"));
  EXPECT_CALL(visitor_, OnHeadersFramePayload("d"));
  EXPECT_CALL(visitor_, OnHeadersFramePayload("e"));
  EXPECT_CALL(visitor_, OnHeadersFramePayload("r"));
  EXPECT_CALL(visitor_, OnHeadersFramePayload("s"));
  EXPECT_CALL(visitor_, OnHeadersFrameEnd());
  for (char c : input) {
    EXPECT_EQ(1u, framer_.ProcessInput(&c, 1));
  }
  EXPECT_EQ(QUIC_NO_ERROR, framer_.error());
  EXPECT_EQ("", framer_.error_detail());
}

}  // namespace quic


text: viiite report bench_iteration --regroup=ruby,bench


text:
<?php

namespace MakeDocs\WebHook\GitHub;

class Config
{
    private $name;
    private $driver;
    private $source;
    private $repository;
    private $builders;

    public function __construct()
    {
        $this->builders = array();
    }

    public function getName()
    {
        return $this->name;
    }

    public function setName($name)
    {
        $this->name = $name;
    }

    public function getDriver()
    {
        return $this->driver;
    }

    public function setDriver($driver)
    {
        $this->driver = $driver;
    }

    public function getSource()
    {
        return $this->source;
    }

    public function setSource($source)
    {
        $this->source = $source;
    }

    public function getRepository()
    {
        return $this->repository;
    }

    public function setRepository($repository)
    {
        $this->repository = $repository;
    }

    public function addBuilder(array $config)
    {
        $this->builders[] = $config;
    }

    public function getBuilders()
    {
        return $this->builders;
    }

    public function setBuilders($builders)
    {
        $this->builders = array();
        foreach ($builders as $builder) {
            $this->addBuilder($builder);
        }
    }
}


text:
package com.careerhub.api.meta;
public final class MetaApi {

		private String baseUrl;

		public MetaApi(String baseUrl) {
			this.baseUrl = baseUrl;
		}

		/*
		public RemoteApiInfo GetApiInfo() {

		}*/
}


text:
<?php

namespace app\repositories\course;

use app\entities\course\CourseMaterial;
use Doctrine\ORM\EntityRepository;

class CourseMaterialRepository extends EntityRepository {
    /**
     * @return CourseMaterial[]
     */
    public function getCourseMaterials(): array {
        $dql = 'SELECT c FROM app\entities\course\CourseMaterial c ORDER BY c.priority ASC, c.path ASC';
        return $this->_em->createQuery($dql)->getResult();
    }
}


text:
//
// Copyright 2020 Google Inc.
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//

// Do not publicly declare C++ methods when compiling in a pure Objective-C environment.
#if __cplusplus

#import <UIKit/UIKit.h>

#include "gtx.pb.h"
#include "typedefs.h"

/**
 *  Additions to NSObject to make it easy to create gtx::UIElements from UIViews and
 *  UIAccessibilityElements.
 */
@interface NSObject (GTXAdditions)

/**
 * Converts this object into a @c UIElementProto. If this object is a subclass of @c NSObject
 * and contains properties declared by @c UIElementProto, those properties are included, too.
 * Does not set parent child relationships of @c UIElementProto.
 * @returns A @c UIElementProto populated by this object's properties.
 */
- (UIElementProto)gtx_toProto;

@end

#endif


text:
LEVEL := ../..
DIRS = llvm bitreader bitwriter irreader analysis target executionengine \
       transforms linker backends all_backends
ExtraMakefiles = $(PROJ_OBJ_DIR)/Makefile.ocaml

ocamldoc:
	$(Verb) for i in $(DIRS) ; do \
		$(MAKE) -C $$i ocamldoc; \
	done

include $(LEVEL)/Makefile.common


text:
#include "Engine.hpp"
#include "AnimationManager.hpp"
#include "FileManager.hpp"
#include "Log.hpp"
#include "Handle.hpp"
#include "Settings.hpp"
#include "Platform.hpp"
#include "Types.hpp"
#include "Util.hpp"
#include "GameObjectManager.hpp"
#include "StoryboardManager.hpp"

namespace Z
{

AnimationManager&
AnimationManager::Instance()
{
    if (!s_pInstance)
    {
        s_pInstance = new AnimationManager();
    }

    return static_cast<AnimationManager&>(*s_pInstance);
}

AnimationManager::AnimationManager()
{
    RETAILMSG(ZONE_VERBOSE, "AnimationManager()");

    s_pResourceManagerName = "AnimationManager";
}

AnimationManager::~AnimationManager()
{
    RETAILMSG(ZONE_VERBOSE, "\t~AnimationManager()");
}

RESULT
AnimationManager::Init( IN const string& settingsFilename )
{
    RETAILMSG(ZONE_INFO, "AnimationManager::Init( %s )", settingsFilename.c_str());

    RESULT rval = S_OK;
    char   path[MAX_PATH];

    //
    // Create a Settings object and load the file.
    //
    Settings mySettings;
    if ( FAILED(mySettings.Read( settingsFilename )) )
    {
        RETAILMSG(ZONE_ERROR, "ERROR: AnimationManager::Init( %s ): failed to load settings file", settingsFilename.c_str() );
        return E_UNEXPECTED;
    }

    //
    // Create each Animation.
    //
    UINT32 numAnimations = mySettings.GetInt("/Animations.NumAnimations");

    for (int i = 0; i < numAnimations; ++i)
    {
        sprintf(path, "/Animations/Animation%d", i);
        //DEBUGMSG(ZONE_INFO, "Loading [%s]", path);

        Animation *pAnimation = NULL;
        CreateAnimation( &mySettings, path, &pAnimation );
        if (!pAnimation)
        {
            RETAILMSG(ZONE_ERROR, "ERROR: AnimationManager::Init( %s ): failed to create Animation", path);

            DEBUGCHK(0);

            // Continue loading other Animations rather than aborting.
            continue;
        }

        //DEBUGMSG(ZONE_ANIMATION, "Created Animation [%s]", pAnimation->GetName().c_str());
        CHR(Add(pAnimation->GetName(), pAnimation));
    }

Exit:
    return rval;
}

RESULT
//AnimationManager::CreateAnimation( IN const string& name, IN KeyFrameType keyFrameType, IN InterpolatorType interpolatorType, IN KeyFrame* pKeyFrames, UINT8 numKeyFrames, bool isRelative, INOUT HAnimation* pHandle )
AnimationManager::CreateAnimation(
        IN const string&            name,
        IN const string&            propertyName,
        IN       PropertyType       propertyType,
        IN       InterpolatorType   interpolatorType,
        IN       KeyFrameType       keyFrameType,
        IN       KeyFrame*          pKeyFrames,
        IN       UINT8              numKeyFrames,
        IN       bool               isRelative,
        INOUT    HAnimation*        pHandle
    )
{
    RESULT      rval = S_OK;
    HAnimation  hAnimation;

    Animation* pAnimation = new Animation();
    if (!pAnimation)
    {
        rval = E_OUTOFMEMORY;
        goto Exit;
    }

    rval = pAnimation->Init( name, propertyName, propertyType, interpolatorType, keyFrameType, pKeyFrames, numKeyFrames, isRelative );
    if (FAILED(rval))
    {
        SAFE_DELETE(pAnimation);
        goto Exit;
    }

    CHR(Add(pAnimation->GetName(), pAnimation, &hAnimation));
    if (pHandle)
    {
        *pHandle = hAnimation;
    }

Exit:
    return rval;
}

RESULT
AnimationManager::CreateAnimation( IN const Settings* pSettings, IN const string& settingsPath, INOUT Animation** ppAnimation )
{
    RESULT rval = S_OK;
    string name;

    if (!pSettings || "" == settingsPath || !ppAnimation)
    {
        RETAILMSG(ZONE_ERROR, "ERROR: AnimationManager::CreateAnimation(): invalid argument");
        return E_INVALID_ARG;
    }

    Animation *pAnimation = new Animation();
    CPR(pAnimation);

    name = pSettings->GetString( settingsPath + ".Name" );

    if ("" == name)
    {
        // Auto-generate the name if needed.
        char instanceName[MAX_PATH];
        sprintf(instanceName, "%s.%s",
            settingsPath.c_str(),
            pSettings->GetString( settingsPath + ".Property" ).c_str());

        name = string(instanceName);
    }

    if (FAILED(pAnimation->Init( name, pSettings, settingsPath )))
    {
        delete pAnimation;
        pAnimation = NULL;
    }

    // Caller must AddRef()
    *ppAnimation = pAnimation;

Exit:
    return rval;
}

RESULT
AnimationManager::ReleaseOnNextFrame( IN HAnimation handle )
{
    RESULT      rval = S_OK;
    Animation*  pAnimation;

    pAnimation = GetObjectPointer( handle );
    if (!pAnimation)
    {
        rval = E_BAD_HANDLE;
        goto Exit;
    }

    CHR(ReleaseOnNextFrame( pAnimation ));

Exit:
    return rval;
}

RESULT
AnimationManager::ReleaseOnNextFrame( IN Animation* pAnimation )
{
    RESULT rval = S_OK;

    CPR(pAnimation)

    m_pendingReleaseAnimationsList.push_back( pAnimation );

Exit:
    return rval;
}

RESULT
AnimationManager::BindTo( IN HAnimation handle, IProperty* pProperty )
{
    RESULT rval = S_OK;

    if (pProperty)
    {
        CHR(BindTo( handle, *pProperty ));
    }
    else
    {
        // Bind to "NULL" - will force the Animation to release its target object.
        static Property<Object> nullProperty;
        CHR(BindTo( handle, nullProperty ));
    }

Exit:
    return rval;
}

RESULT
AnimationManager::BindTo( IN HAnimation handle, IProperty& property )
{
    RESULT      rval = S_OK;
    Animation*  pAnimation;

//    if ( property.IsNull() )
//    {
//        RETAILMSG(ZONE_ERROR, "ERROR: AnimationManager::BindTo( %d, 0x%x ): property IsNull",
//            (UINT32)handle, (UINT32)&property);
//
//        rval = E_INVALID_ARG;
//        goto Exit;
//    }

    pAnimation = GetObjectPointer( handle );
    if (!pAnimation)
    {
        rval = E_BAD_HANDLE;
        goto Exit;
    }

    // If the property is NULL, the Animation will
    // release any target object it was previously bound to.
    CHR(pAnimation->BindTo( property ));

Exit:
    return rval;
}

RESULT
AnimationManager::SetAutoRepeat( IN HAnimation handle, bool willAutoRepeat )
{
    RESULT rval = S_OK;

    Animation* pAnimation = GetObjectPointer( handle );
    if (!pAnimation)
    {
        rval = E_BAD_HANDLE;
        goto Exit;
    }

     CHR(pAnimation->SetAutoRepeat( willAutoRepeat ));

Exit:
    return rval;
}

RESULT
AnimationManager::SetAutoReverse( IN HAnimation handle, bool willAutoReverse )
{
    RESULT rval = S_OK;

    Animation* pAnimation = GetObjectPointer( handle );
    if (!pAnimation)
    {
        rval = E_BAD_HANDLE;
        goto Exit;
    }

     CHR(pAnimation->SetAutoReverse( willAutoReverse ));

Exit:
    return rval;
}

RESULT
AnimationManager::SetDeleteOnFinish( IN HAnimation handle, bool willDeleteOnFinish )
{
    RESULT rval = S_OK;

    Animation* pAnimation = GetObjectPointer( handle );
    if (!pAnimation)
    {
        rval = E_BAD_HANDLE;
        goto Exit;
    }

     CHR(pAnimation->SetDeleteOnFinish( willDeleteOnFinish ));

Exit:
    return rval;
}

RESULT
AnimationManager::CallbackOnFinished( IN HAnimation handle, ICallback& callback )
{
    RESULT      rval = S_OK;
    Animation*  pAnimation;

    if ( callback.IsNull() )
    {
        RETAILMSG(ZONE_ERROR, "ERROR: AnimationManager::CallbackOnFinished( %d, 0x%x ): callback IsNull",
            (UINT32)handle, (UINT32)&callback);

        rval = E_INVALID_ARG;
        goto Exit;
    }

    pAnimation = GetObjectPointer( handle );
    if (!pAnimation)
    {
        rval = E_BAD_HANDLE;
        goto Exit;
    }

    CHR(pAnimation->CallbackOnFinished( callback ));

Exit:
    return rval;
}

RESULT
AnimationManager::Start( IN HAnimation handle )
{
    RESULT rval = S_OK;

    // Get the animation, add it to m_runningAnimationsList if not already started
    Animation* pAnimation = GetObjectPointer( handle );
    if (pAnimation && !pAnimation->IsStarted())
    {
        m_runningAnimationsList.push_back(pAnimation);
    }

    if (pAnimation)
    {
        RETAILMSG(ZONE_ANIMATION | ZONE_VERBOSE, "AnimationManager::Start( \"%s\" )", pAnimation->GetName().c_str());
        pAnimation->Start();
    }
    else
    {
        rval = E_FAIL;
    }

Exit:
    return rval;
}

RESULT
AnimationManager::Stop( IN HAnimation handle )
{
    RESULT rval = S_OK;

    Animation* pAnimation = GetObjectPointer( handle );
    if (pAnimation && pAnimation->IsStarted())
    {
        RETAILMSG(ZONE_ANIMATION, "AnimationManager::Stop( \"%s\" )", pAnimation->GetName().c_str());
        pAnimation->Stop();

        AnimationListIterator ppAnimation;
        ppAnimation = find( m_runningAnimationsList.begin(), m_runningAnimationsList.end(), pAnimation );

        if (ppAnimation != m_runningAnimationsList.end())
        {
            m_runningAnimationsList.erase( ppAnimation );
        }
    }
    else
    {
        rval = E_FAIL;
    }

Exit:
    return rval;
}

RESULT
AnimationManager::Pause( IN HAnimation handle )
{
    RESULT rval = S_OK;

    Animation* pAnimation = GetObjectPointer( handle );
    if (pAnimation && !pAnimation->IsStarted())
    {
        RETAILMSG(ZONE_ANIMATION | ZONE_VERBOSE, "AnimationManager::Pause( \"%s\" )", pAnimation->GetName().c_str());
        pAnimation->Pause();

        AnimationListIterator ppAnimation;
        ppAnimation = find( m_runningAnimationsList.begin(), m_runningAnimationsList.end(), pAnimation );

        if (ppAnimation != m_runningAnimationsList.end())
        {
            m_runningAnimationsList.erase( ppAnimation );
        }
    }
    else
    {
        rval = E_FAIL;
    }

Exit:
    return rval;
}

RESULT
AnimationManager::Update( UINT64 elapsedMS )
{
    RESULT rval = S_OK;

    // Release Animations that were marked as done on previous frame.
    AnimationListIterator ppAnimation;
    for (ppAnimation = m_pendingReleaseAnimationsList.begin(); ppAnimation != m_pendingReleaseAnimationsList.end(); ++ppAnimation)
    {
        Animation* pAnimation = *ppAnimation;

        DEBUGMSG(ZONE_ANIMATION | ZONE_VERBOSE, "Releasing Animation [%s]", pAnimation->GetName().c_str());

        CHR(Release( pAnimation ));
    }
    m_pendingReleaseAnimationsList.clear();

    // Update running animation, which in turn will update its bound AnimationTarget
    for (ppAnimation = m_runningAnimationsList.begin(); ppAnimation != m_runningAnimationsList.end(); ++ppAnimation)
    {
        Animation* pAnimation = *ppAnimation;

        DEBUGMSG(ZONE_ANIMATION | ZONE_VERBOSE, "Ticking Animation [%s]", pAnimation->GetName().c_str());

        pAnimation->Update( elapsedMS );
    }

Exit:
    return rval;
}

RESULT
AnimationManager::Update( IN HAnimation handle, UINT64 elapsedMS )
{
    RESULT rval = S_OK;

    Animation* pAnimation = GetObjectPointer( handle );
    if (pAnimation && pAnimation->IsStarted())
    {
        //RETAILMSG(ZONE_ANIMATION | ZONE_VERBOSE, "AnimationManager::Update( \"%s\" )", pAnimation->GetName().c_str());

        CHR(pAnimation->Update( elapsedMS ));
    }
    else
    {
        rval = E_FAIL;
    }

Exit:
    return rval;
}

UINT64
AnimationManager::GetDurationMS( IN HAnimation handle )
{
    UINT64 rval = 0;

    Animation* pAnimation = GetObjectPointer( handle );
    if (pAnimation)
    {
        rval = pAnimation->GetDurationMS();
    }

Exit:
    return rval;
}

UINT8
AnimationManager::GetNumKeyframes( IN HAnimation handle )
{
    UINT8 rval = 0;

    Animation* pAnimation = GetObjectPointer( handle );
    if (pAnimation)
    {
        rval = pAnimation->GetNumKeyFrames();
    }

Exit:
    return rval;
}

PropertyType
AnimationManager::GetPropertyType( IN HAnimation handle )
{
    PropertyType rval = PROPERTY_UNKNOWN;

    Animation* pAnimation = GetObjectPointer( handle );
    if (pAnimation)
    {
        rval = pAnimation->GetPropertyType();
    }

Exit:
    return rval;
}

const string&
AnimationManager::GetPropertyName( IN HAnimation handle )
{
    static string emptystr = "";

    Animation* pAnimation = GetObjectPointer( handle );
    if (pAnimation)
    {
        return pAnimation->GetPropertyName();
    }
    else
    {
        return emptystr;
    }
}

} // END namespace Z


text:
package com.cloudata.files.webdav;

import javax.activation.MimetypesFileTypeMap;
import javax.inject.Singleton;

@Singleton
public class MimeHelper {
    final MimetypesFileTypeMap mimeTypesMap = new MimetypesFileTypeMap();

    public String getMimeType(String fileName) {
        return mimeTypesMap.getContentType(fileName);
    }
}


text:
package synergyviewcore.attributes.ui.wizards;

import java.util.UUID;

import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.wizard.Wizard;
import org.eclipse.ui.IWorkbench;
import org.eclipse.ui.IWorkbenchWizard;

import synergyviewcore.attributes.model.Attribute;
import synergyviewcore.attributes.model.AttributeNode;
import synergyviewcore.navigation.model.INode;
import synergyviewcore.projects.model.ProjectNode;

/**
 * The Class NewAttributeWizard.
 *
 * @author phyo
 */
public class NewAttributeWizard extends Wizard implements IWorkbenchWizard {

    /** The main page. */
    private NewAttributeWizardPage mainPage;

    /** The new attribute. */
    private Attribute newAttribute;

    /** The parent node. */
    private INode parentNode = null;

    /**
     * Instantiates a new new attribute wizard.
     */
    public NewAttributeWizard() {
	super();
    }

    /*
     * (non-Javadoc)
     *
     * @see org.eclipse.jface.wizard.IWizard#addPages()
     */
    public void addPages() {
	super.addPages();
	addPage(mainPage);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.eclipse.ui.IWorkbenchWizard#init(org.eclipse.ui.IWorkbench, org.eclipse.jface.viewers.IStructuredSelection)
     */
    public void init(IWorkbench arg0, IStructuredSelection arg1) {
	if (arg1 != StructuredSelection.EMPTY) {
	    parentNode = (INode) arg1.getFirstElement();
	}
	newAttribute = new Attribute();
	newAttribute.setId(UUID.randomUUID().toString());
	mainPage = new NewAttributeWizardPage("New Attribute Page", newAttribute);
    }

    /*
     * (non-Javadoc)
     *
     * @see org.eclipse.jface.wizard.Wizard#performFinish()
     */
    @Override
    public boolean performFinish() {

	if (parentNode instanceof AttributeNode) {
	    ((ProjectNode) parentNode.getLastParent()).getProjectAttributeRootNode().addAttribute(newAttribute, ((AttributeNode) parentNode).getResource());
	} else {
	    ((ProjectNode) parentNode.getLastParent()).getProjectAttributeRootNode().addAttribute(newAttribute, null);
	}
	return true;
    }

}


text:
require 'rails_helper'

describe Message do
  it { should validate_presence_of :text }
  it { should validate_presence_of :username }
  it { should validate_length_of(:text).is_at_most(400) }
end


text:
Extending the page & title models
#################################

.. versionadded:: 3.0

You can extend the page and title models with your own fields (e.g. adding
an icon for every page) by using the extension models:
``cms.extensions.PageExtension`` and ``cms.extensions.TitleExtension``,
respectively.

What's the difference?
======================

The difference between a page extension and a title extension is related to
the difference between the Page and Title models. Titles support pages by
providing a storage mechanism, among other things, for language-specific
properties of Pages. So, if you find that you need to extend the page model in
a language-specific manner, for example, if you need to create language-
specific keywords for each language of your pages, then you may need to use a
TitleExtension. If the extension you'd like to create is the same for all of
the different languages of the page, then you may be fine using a
PageExtension.

******
How To
******

To add a field to the page model, create a class that inherits from
``cms.extensions.PageExtension``. Make sure to import the
``cms.extensions.PageExtension`` model. Your class should live in one of your
apps' ``models.py`` (or module). Since ``PageExtension`` (and
``TitleExtension``) inherit from ``django.db.models.Model``, you are free to
add any field you want but make sure you don't use a unique constraint on any
of your added fields because uniqueness prevents the copy mechanism of the
extension from working correctly. This means that you can't use one-to-one
relations on the extension model. Finally, you'll need to register the model
with using ``extension_pool``.

Here's a simple example which adds an ``icon`` field to the page::

    from django.db import models

    from cms.extensions import PageExtension
    from cms.extensions.extension_pool import extension_pool

    class IconExtension(PageExtension):
        image = models.ImageField(upload_to='icons')

    extension_pool.register(IconExtension)

Hooking the extension to the admin site
=======================================

To make your extension editable, you must first create an admin class that
subclasses ``cms.extensions.PageExtensionAdmin``. This admin handles page
permissions. If you want to use your own admin class, make sure to exclude the
live versions of the extensions by using
``filter(extended_page__publisher_is_draft=True)`` on the queryset.

Continuing with the example model above, here's a simple corresponding
``PageExtensionAdmin`` class::

    from django.contrib import admin
    from cms.extensions import PageExtensionAdmin

    from .models import IconExtension

    class IconExtensionAdmin(PageExtensionAdmin):
        pass

    admin.site.register(IconExtension, IconExtensionAdmin)

Since PageExtensionAdmin inherits from ModelAdmin, you'll be able to use the
normal set of Django ModelAdmin properties, as appropriate to your
circumstance.

Once you've registered your admin class, a new model will appear in the top-
level admin list.

Note that the field that holds the relationship between the extension and a
CMS Page is non-editable, so it will not appear in the admin views. This,
unfortunately, leaves the operator without a means of "attaching" the page
extension to the correct pages. The way to address this is to use a
CMSToolbar. Note that creating the admin hook is still required, because it
creates the add and change admin forms that are required for the next step.

Adding a Toolbar Menu Item for your Page extension
==================================================

You'll also want to make your model editable from the cms toolbar in order to
associate each instance of the extension model with a page. (Page isn't an
editable attribute in the default admin interface.).
To add toolbar items for your extension create a file named ``cms_toolbar.py``
in one of your apps, and add the relevant menu entries for the extension on each page.

**********************
Simplified toolbar API
**********************

.. versionadded:: 3.0.6

Since 3.0.6 a simplified toolbar API is available to handle the more common cases::

    from cms.toolbar_pool import toolbar_pool
    from cms.extensions.toolbar import ExtensionToolbar
    from django.utils.translation import ugettext_lazy as _
    from .models import IconExtension

    @toolbar_pool.register
    class IconExtensionToolbar(ExtensionToolbar):
        # defineds the model for the current toolbar
        model = IconExtension

        def populate(self):
            # setup the extension toolbar with permissions and sanity checks
            current_page_menu = self._setup_extension_toolbar()
            # if it's all ok
            if current_page_menu:
                # retrieves the instance of the current extension (if any) and the toolbar item url
                page_extension, url = self.get_page_extension_admin()
                if url:
                    # adds a toolbar item
                    current_page_menu.add_modal_item(_('Page Icon'), url=url,
                        disabled=not self.toolbar.edit_mode)

Similarly for title extensions::

    from cms.extensions.toolbar import ExtensionToolbar
    from django.utils.translation import ugettext_lazy as _
    from .models import TitleIconExtension

    @toolbar_pool.register
    class TitleIconExtensionToolbar(ExtensionToolbar):
        # setup the extension toolbar with permissions and sanity checks
        model = TitleIconExtension

        def populate(self):
            # setup the extension toolbar with permissions and sanity checks
            current_page_menu = self._setup_extension_toolbar()
            # if it's all ok
            if current_page_menu and self.toolbar.edit_mode:
                # create a sub menu
                position = 0
                sub_menu = self._get_sub_menu(current_page_menu, 'submenu_label', 'Submenu', position)
                # retrieves the instances of the current title extension (if any) and the toolbar item url
                urls = self.get_title_extension_admin()
                # cycle through the title list
                for title_extension, url in urls:
                    # adds toolbar items
                    sub_menu.add_modal_item('icon for title %s' % self._page().get_title(),
                                            url=url, disabled=not self.toolbar.edit_mode)

For details see the :ref:`reference <simplified_extension_toolbar>`

********************
Complete toolbar API
********************

If you need complete control over the layout of your extension toolbar items you can still use the
low-level API to edit the toolbar according to your needs::

    from cms.api import get_page_draft
    from cms.toolbar_pool import toolbar_pool
    from cms.toolbar_base import CMSToolbar
    from cms.utils import get_cms_setting
    from cms.utils.permissions import has_page_change_permission
    from django.core.urlresolvers import reverse, NoReverseMatch
    from django.utils.translation import ugettext_lazy as _
    from .models import IconExtension

    @toolbar_pool.register
    class IconExtensionToolbar(CMSToolbar):
        def populate(self):
            # always use draft if we have a page
            self.page = get_page_draft(self.request.current_page)

            if not self.page:
                # Nothing to do
                return

            # check global permissions if CMS_PERMISSION is active
            if get_cms_setting('PERMISSION'):
                has_global_current_page_change_permission = has_page_change_permission(self.request)
            else:
                has_global_current_page_change_permission = False
                # check if user has page edit permission
            can_change = self.request.current_page and self.request.current_page.has_change_permission(self.request)
            if has_global_current_page_change_permission or can_change:
                try:
                    icon_extension = IconExtension.objects.get(extended_object_id=self.page.id)
                except IconExtension.DoesNotExist:
                    icon_extension = None
                try:
                    if icon_extension:
                        url = reverse('admin:myapp_iconextension_change', args=(icon_extension.pk,))
                    else:
                        url = reverse('admin:myapp_iconextension_add') + '?extended_object=%s' % self.page.pk
                except NoReverseMatch:
                    # not in urls
                    pass
                else:
                    not_edit_mode = not self.toolbar.edit_mode
                    current_page_menu = self.toolbar.get_or_create_menu('page')
                    current_page_menu.add_modal_item(_('Page Icon'), url=url, disabled=not_edit_mode)

Now when the operator invokes "Edit this page..." from the toolbar, there will
be an additional menu item ``Page Icon ...`` (in this case), which can be used
to open a modal dialog where the operator can affect the new ``icon`` field.

Note that when the extension is saved, the corresponding page is marked as
having unpublished changes. To see the new extension values make sure to
publish the page.

Using extensions with menus
===========================

If you want the extension to show up in the menu (e.g. if you had created an
extension that added an icon to the page) use menu modifiers. Every ``node.id``
corresponds to their related ``page.id``. ``Page.objects.get(pk=node.id)`` is
the way to get the page object. Every page extension has a one-to-one
relationship with the page so you can access it by using the reverse relation,
e.g. ``extension = page.yourextensionlowercased``. Now you can hook this
extension by storing it on the node: ``node.extension = extension``. In the
menu template you can access your icon on the child object:
``child.extension.icon``.

Using extensions in templates
=============================

To access a page extension in page templates you can simply access the
approriate related_name field that is now available on the Page object.

As per the normal related_name naming mechanism, the appropriate field to
access is the same as your PageExtension model name, but lowercased. Assuming
your Page Extension model class is ``IconExtension``, the relationship to the
page extension model will be available on ``page.iconextension``. From there
you can access the extra fields you defined in your extension, so you can use
something like::

    {% load staticfiles %}

    {# rest of template omitted ... #}

    {% if request.current_page.iconextension %}
        <img src="{% static request.current_page.iconextension.image.url %}">
    {% endif %}

Where ``request.current_page`` is the normal way to access the current page
that is rendering the template.

It is important to remember that unless the operator has already assigned a
page extension to every page, a page may not have the iconextension
relationship available, hence the use of the ``{% if ... %}...{% endif %}``
above.

Handling relations
==================

If your PageExtension or TitleExtension includes a ForeignKey *from* another
model or includes a ManyToMany field, you should also override the method
``copy_relations(self, oldinstance, language)`` so that these fields are
copied appropriately when the CMS makes a copy of your extension to support
versioning, etc.

Here's an example that uses a `ManyToMany`` field::

    from django.db import models
    from cms.extensions import PageExtension
    from cms.extensions.extension_pool import extension_pool

    class MyPageExtension(PageExtension):

        page_categories = models.ManyToMany('categories.Category', blank=True, null=True)

        def copy_relations(self, oldinstance, language):
            for page_category in oldinstance.page_categories.all():
                page_category.pk = None
                page_category.mypageextension = self
                page_category.save()

    extension_pool.register(MyPageExtension)

.. _simplified_extension_toolbar:

Simplified Toolbar API
======================

The simplified Toolbar API works by deriving your toolbar class from ``ExtensionToolbar``
which provides the following API:

* :py:meth:`cms.extensions.toolbar.ExtensionToolbar._setup_extension_toolbar`: this must be called first to setup
  the environment and do the permission checking;
* :py:meth:`cms.extensions.toolbar.ExtensionToolbar.get_page_extension_admin`: for page extensions, retrieves the
  correct admin url for the related toolbar item; returns the extension instance (or `None` if not exists)
  and the admin url for the toolbar item;
* :py:meth:`cms.extensions.toolbar.ExtensionToolbar.get_title_extension_admin`: for title extensions, retrieves the
  correct admin url for the related toolbar item; returns a list of the extension instances
  (or `None` if not exists) and the admin urls for each title of the current page;


text:
using System;
using System.ComponentModel.DataAnnotations.Schema;
using System.Threading.Tasks;
using Abp.Domain.Entities;
using Abp.Domain.Entities.Auditing;
using Abp.Domain.Repositories;
using Abp.UI;
using EventCloud.Users;

namespace EventCloud.Events
{
    [Table("AppEventRegistrations")]
    public class EventRegistration : CreationAuditedEntity, IMustHaveTenant
    {
        public int TenantId { get; set; }

        [ForeignKey("EventId")]
        public virtual Event Event { get; protected set; }
        public virtual Guid EventId { get; protected set; }

        [ForeignKey("UserId")]
        public virtual User User { get; protected set; }
        public virtual long UserId { get; protected set; }

        /// <summary>
        /// We don't make constructor public and forcing to create registrations using <see cref="CreateAsync"/> method.
        /// But constructor can not be private since it's used by EntityFramework.
        /// Thats why we did it protected.
        /// </summary>
        protected EventRegistration()
        {

        }

        public async static Task<EventRegistration> CreateAsync(Event @event, User user, IEventRegistrationPolicy registrationPolicy)
        {
            if (@event == null) { throw new ArgumentNullException("event"); }
            if (user == null) { throw new ArgumentNullException("user"); }
            if (registrationPolicy == null) { throw new ArgumentNullException("registrationPolicy"); }

            await registrationPolicy.CheckRegistrationAttemptAsync(@event, user);

            return new EventRegistration
            {
                TenantId = @event.TenantId,
                EventId = @event.Id,
                Event = @event,
                UserId = @user.Id,
                User = user
            };
        }

        public async Task CancelAsync(IRepository<EventRegistration> repository)
        {
            if (repository == null) { throw new ArgumentNullException("repository"); }

            if (Event.IsInPast())
            {
                throw new UserFriendlyException("Can not cancel event which is in the past!"); //TODO: Localize
            }

            if (Event.IsAllowedCancellationTimeEnded())
            {
                throw new UserFriendlyException("It's too late to cancel your registration!"); //TODO: Localize
            }

            await repository.DeleteAsync(this);
        }
    }
}


text:
declare namespace javax {
  namespace swing {
    namespace plaf {
      namespace metal {

        class MetalToolBarUI extends javax.swing.plaf.basic.BasicToolBarUI {
          protected contListener: java.awt.event.ContainerListener
          protected rolloverListener: java.beans.PropertyChangeListener
          public constructor()
          static register(arg0: javax.swing.JComponent): void
          static unregister(arg0: javax.swing.JComponent): void
          static findRegisteredComponentOfType(arg0: javax.swing.JComponent, arg1: java.lang.Class<unknown>): java.lang.Object
          static doesMenuBarBorderToolBar(arg0: javax.swing.JMenuBar): boolean
          public static createUI(arg0: javax.swing.JComponent): javax.swing.plaf.ComponentUI
          public installUI(arg0: javax.swing.JComponent): void
          public uninstallUI(arg0: javax.swing.JComponent): void
          protected installListeners(): void
          protected uninstallListeners(): void
          protected createRolloverBorder(): javax.swing.border.Border
          protected createNonRolloverBorder(): javax.swing.border.Border
          protected setBorderToNonRollover(arg0: java.awt.Component): void
          protected createContainerListener(): java.awt.event.ContainerListener
          protected createRolloverListener(): java.beans.PropertyChangeListener
          protected createDockingListener(): javax.swing.event.MouseInputListener
          protected setDragOffset(arg0: java.awt.Point): void
          public update(arg0: java.awt.Graphics, arg1: javax.swing.JComponent): void
        }

      }
    }
  }
}


text:
#ifndef DELTA_CORE_STATE_H_
#define DELTA_CORE_STATE_H_

#include <time.h>
#include <vector>
#include <fstream>
#include <string>
#include <chrono>
#include <iomanip>
#include <iostream>
#include "data/Structure.h"
#include "data/Meta.h"

typedef std::chrono::steady_clock Time;
typedef std::chrono::duration<float> fsec;

namespace delta {
	namespace core {
		class State;
	}
}

class delta::core::State {
  public:
	State();

	State(
		  delta::core::data::Structure& 			datastructure,
		  delta::core::data::Meta::Simulation& 		meta);

	void 	initCheckpoint(int iteration);
	void 	closeCheckpoint();
	void 	readState();
	void 	writeState();
	void 	saveParticleGeometry();
	void 	update();

	int 		getCurrentStepIteration();
	int 		getCollisions();
	iREAL 	getStepSize();

	void 	incNumberOfTriangleComparisons(int n);
	void 	incNumberOfParticleComparisons(int n);

	std::chrono::steady_clock::time_point getStartTime();

	iREAL getCurrentTime();

	void log();
	void termination();
  private:
	//physical simulation
	int 		_noOfParticles;
	int 		_noOfObstacles;
	iREAL 	_dt;
	int 		_numberOfTriangleComparisons;
	int 		_numberOfParticleComparisons;
	int 		_numberOfCollisions;

	//engine
	int 		_iteration;

	std::chrono::steady_clock::time_point _start;

	//std::ofstream 	_checkpointFile;
};

#endif /* DELTA_CORE_STATE_H_ */


text:
// Licensed to the .NET Foundation under one or more agreements.
// The .NET Foundation licenses this file to you under the MIT license.
// See the LICENSE file in the project root for more information.

#pragma once

#include "pal_types.h"
#include <sys/types.h>

/**
* Passwd struct
*/
struct Passwd
{
    char* Name;
    char* Password;
    uint32_t UserId;
    uint32_t GroupId;
    char* UserInfo;
    char* HomeDirectory;
    char* Shell;
};

/**
* Gets a password structure for the given uid.
* Implemented as shim to getpwuid_r(3).
*
* Returns 0 for success, -1 if no entry found, positive error
* number for any other failure.
*
*/
extern "C" int32_t SystemNative_GetPwUidR(uint32_t uid, Passwd* pwd, char* buf, int32_t buflen);

/**
* Gets and returns the effective user's identity.
* Implemented as shim to geteuid(2).
*
* Always succeeds.
*/
extern "C" uint32_t SystemNative_GetEUid();

/**
* Gets and returns the effective group's identity.
* Implemented as shim to getegid(2).
*
* Always succeeds.
*/
extern "C" uint32_t SystemNative_GetEGid();

/**
* Sets the effective user ID of the calling process
* Implemented as a shim to seteuid(2).
*
* Returns 0 for success. On error, -1 is returned and errno is set.
*/
extern "C" int32_t SystemNative_SetEUid(uid_t euid);


text:
namespace engine {

TimeManager::time_point TimeManager::currentTime() noexcept
{
	return _currentTime;
}

TimeManager::time_point TimeManager::lastFrameTime() noexcept
{
	return _lastFrameTime;
}

void TimeManager::setGameRate( float iRate )
{
	_sessionTimer.setRate(iRate);
}

TimeManager::TimeManager()
	: _lastFrameTime()
	, _currentTime()
	, _sessionTimer()
{
	_sessionTimer.reset();
}

void TimeManager::startFrame()
{
	_lastFrameTime = _currentTime;
	_currentTime = _sessionTimer.now();
}

void TimeManager::startSession()
{
	_currentTime = TimeManager::time_point::min();
	_lastFrameTime = TimeManager::time_point::min();
	_sessionTimer.reset(1.0f);
}
} // namespace engine


text:
namespace display {

class Screen;

namespace test {

// This class represents a RAII wrapper for global screen overriding. An object
// of this class restores original display::Screen instance when it goes out of
// scope. Prefer to use it instead of directly call of
// display::Screen::SetScreenInstance().
class ScopedScreenOverride {
 public:
  explicit ScopedScreenOverride(Screen* screen);
  ~ScopedScreenOverride();

 private:
  Screen* original_screen_;
  DISALLOW_COPY_AND_ASSIGN(ScopedScreenOverride);
};

}  // namespace test
}  // namespace display

#endif  // UI_DISPLAY_TEST_SCOPED_SCREEN_OVERRIDE_H_


text:
Not usable. This is just a playground for me to experiment with the shrinking
techniques described
[here](http://projects.haskell.org/pipermail/quickcheck/2013-November/000115.html)
and
[here](http://www.haskell.org/pipermail/libraries/2013-November/021674.html).
If it's successful, I'll try and get these changes merged into the canonical
Haskell QuickCheck.

## Installation

```bash
cabal sandbox init
cabal install --only-dependencies -j --enable-tests
cabal build && cabal test
```


text:
package utils

import (
	"errors"
)

type State int

const (
	INITIAL State = iota
	NORMALCHAR
	SEPARATOR
	QUOTE
)

func Split(source string, separator rune, quote rune) ([]string, error) {
	var result []string
	var err error

	state := INITIAL
	var word []rune
	for _, c := range source {
		switch state {
		case INITIAL:
			if c == quote {
				state = QUOTE
				word = append(word, c)
			} else if c == separator {
				state = SEPARATOR
			} else {
				state = NORMALCHAR
				word = append(word, c)
			}
		case NORMALCHAR:
			if c == quote {
				state = QUOTE
				word = append(word, c)
			} else if c == separator {
				state = SEPARATOR
				result = append(result, string(word))
				word = []rune{}
			} else {
				word = append(word, c)
			}
		case QUOTE:
			word = append(word, c)
			if c == quote {
				state = NORMALCHAR
			}
		case SEPARATOR:
			if c == quote {
				state = QUOTE
				word = append(word, c)
			} else if c != separator {
				state = NORMALCHAR
				word = append(word, c)
			}
		default:
			state = INITIAL
			err = errors.New("PARSE ERROR : Unknown State.")
		}
	}

	if len(word) > 0 {
		result = append(result, string(word))
	}

	if state == QUOTE {
		err = errors.New("PARSE ERROR : Unmatched " + string(quote) + ".")
	}

	return result, err
}