text:
from optparse import make_option

from django.conf import settings
from django.core.cache import caches
from django.core.cache.backends.db import BaseDatabaseCache
from django.core.management.base import BaseCommand, CommandError
from django.db import connections, router, transaction, models, DEFAULT_DB_ALIAS
from django.db.utils import DatabaseError
from django.utils.encoding import force_text

class Command(BaseCommand):
    help = "Creates the tables needed to use the SQL cache backend."

    option_list = BaseCommand.option_list + (
        make_option('--database', action='store', dest='database',
            default=DEFAULT_DB_ALIAS, help='Nominates a database onto '
                'which the cache tables will be installed. '
                'Defaults to the "default" database.'),
    )

    requires_model_validation = False

    def handle(self, *tablenames, **options):
        db = options.get('database')
        self.verbosity = int(options.get('verbosity'))
        if len(tablenames):
            # Legacy behavior, tablename specified as argument
            for tablename in tablenames:
                self.create_table(db, tablename)
        else:
            for cache_alias in settings.CACHES:
                cache = caches[cache_alias]
                if isinstance(cache, BaseDatabaseCache):
                    self.create_table(db, cache._table)

    def create_table(self, database, tablename):
        cache = BaseDatabaseCache(tablename, {})
        if not router.allow_migrate(database, cache.cache_model_class):
            return
        connection = connections[database]

        if tablename in connection.introspection.table_names():
            if self.verbosity > 0:
                self.stdout.write("Cache table '%s' already exists." % tablename)
            return

        fields = (
            # "key" is a reserved word in MySQL, so use "cache_key" instead.
            models.CharField(name='cache_key', max_length=255, unique=True, primary_key=True),
            models.TextField(name='value'),
            models.DateTimeField(name='expires', db_index=True),
        )
        table_output = []
        index_output = []
        qn = connection.ops.quote_name
        for f in fields:
            field_output = [qn(f.name), f.db_type(connection=connection)]
            field_output.append("%sNULL" % ("NOT " if not f.null else ""))
            if f.primary_key:
                field_output.append("PRIMARY KEY")
            elif f.unique:
                field_output.append("UNIQUE")
            if f.db_index:
                unique = "UNIQUE " if f.unique else ""
                index_output.append("CREATE %sINDEX %s ON %s (%s);" %
                    (unique, qn('%s_%s' % (tablename, f.name)), qn(tablename),
                    qn(f.name)))
            table_output.append(" ".join(field_output))
        full_statement = ["CREATE TABLE %s (" % qn(tablename)]
        for i, line in enumerate(table_output):
            full_statement.append('    %s%s' % (line, ',' if i < len(table_output) - 1 else ''))
        full_statement.append(');')
        with transaction.commit_on_success_unless_managed():
            curs = connection.cursor()
            try:
                curs.execute("\n".join(full_statement))
            except DatabaseError as e:
                raise CommandError(
                    "Cache table '%s' could not be created.\nThe error was: %s." %
                    (tablename, force_text(e)))
            for statement in index_output:
                curs.execute(statement)
        if self.verbosity > 1:
            self.stdout.write("Cache table '%s' created." % tablename)


text:
using System.Collections.Concurrent;
using System.Collections.Immutable;
using System.Text.RegularExpressions;

using Microsoft.Recognizers.Definitions.French;

namespace Microsoft.Recognizers.Text.Number.French
{
    public class NumberExtractor : BaseNumberExtractor
    {
        internal sealed override ImmutableDictionary<Regex, TypeTag> Regexes { get; }

        protected sealed override string ExtractType { get; } = Constants.SYS_NUM;

        private static readonly ConcurrentDictionary<(NumberMode, NumberOptions), NumberExtractor> Instances =
            new ConcurrentDictionary<(NumberMode, NumberOptions), NumberExtractor>();

        public static NumberExtractor GetInstance(NumberMode mode = NumberMode.Default,
            NumberOptions options = NumberOptions.None)
        {

            var cacheKey = (mode, options);
            if (!Instances.ContainsKey(cacheKey))
            {
                var instance = new NumberExtractor(mode);
                Instances.TryAdd(cacheKey, instance);
            }

            return Instances[cacheKey];
        }

        public NumberExtractor(NumberMode mode = NumberMode.Default)
        {
            var builder = ImmutableDictionary.CreateBuilder<Regex, TypeTag>();

            CardinalExtractor cardExtract = null;
            switch(mode)
            {
                case NumberMode.PureNumber:
                    cardExtract = new CardinalExtractor(NumbersDefinitions.PlaceHolderPureNumber);
                    break;
                case NumberMode.Currency:
                    builder.Add(new Regex(NumbersDefinitions.CurrencyRegex, RegexOptions.Singleline),
                                RegexTagGenerator.GenerateRegexTag(Constants.INTEGER_PREFIX, Constants.NUMBER_SUFFIX));
                    break;
                case NumberMode.Default:
                    break;
            }

            if (cardExtract == null)
            {
                cardExtract = new CardinalExtractor();
            }

            builder.AddRange(cardExtract.Regexes);

            var fracExtract = new FractionExtractor();
            builder.AddRange(fracExtract.Regexes);

            Regexes = builder.ToImmutable();
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
<?php /* Smarty version Smarty3-b8, created on 2011-05-26 12:41:47
         compiled from "D:\htdocs\yulog.net.shehua\wholesale/Template/Quote.html" */ ?>
<?php /*%%SmartyHeaderCode:271324dddda0be96688-48816461%%*/if(!defined('SMARTY_DIR')) exit('no direct access allowed');
$_smarty_tpl->decodeProperties(array (
  'file_dependency' =>
  array (
    'baf39d2a5fce6b3c31f7e28043b8dfb3e17362fc' =>
    array (
      0 => 'D:\\htdocs\\yulog.net.shehua\\wholesale/Template/Quote.html',
      1 => 1306134264,
    ),
  ),
  'nocache_hash' => '271324dddda0be96688-48816461',
  'function' =>
  array (
  ),
  'has_nocache_code' => false,
)); /*/%%SmartyHeaderCode%%*/?>
<?php if (!is_callable('smarty_function_write_url')) include 'D:\htdocs\yulog.net.shehua\smarty\plugins\function.write_url.php';
if (!is_callable('smarty_function_CLASS_COLOR')) include 'D:\htdocs\yulog.net.shehua\smarty\plugins\function.CLASS_COLOR.php';
?><!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>奢华</title>
<link href="css/default.css" rel="stylesheet" type="text/css" />

		<?php $_template = new Smarty_Internal_Template("nav.html", $_smarty_tpl->smarty, $_smarty_tpl, $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, null, null);
 echo $_template->getRenderedTemplate();?><?php $_template->updateParentVariables(0);?><?php unset($_template);?>

<a href="<?php echo smarty_function_write_url(array('url'=>$_smarty_tpl->getVariable('thisurl')->value,'action'=>'Prints','exchange'=>$_smarty_tpl->getVariable('get')->value['exchange']),$_smarty_tpl->smarty,$_smarty_tpl);?>
" class="Print" target="_<?php echo $_smarty_tpl->getVariable('get')->value['exchange'];?>
">打印 (<?php echo $_smarty_tpl->getVariable('get')->value['exchange'];?>
) 报价

				<a href="<?php echo smarty_function_write_url(array('open'=>'Quote','exchange'=>'USD'),$_smarty_tpl->smarty,$_smarty_tpl);?>
" <?php echo smarty_function_CLASS_COLOR(array('USD'=>$_smarty_tpl->getVariable('get')->value['exchange'],'CLASS'=>'this'),$_smarty_tpl->smarty,$_smarty_tpl);?>
>美元
				<a href="<?php echo smarty_function_write_url(array('open'=>'Quote','exchange'=>'CNY'),$_smarty_tpl->smarty,$_smarty_tpl);?>
" <?php echo smarty_function_CLASS_COLOR(array('CNY'=>$_smarty_tpl->getVariable('get')->value['exchange'],'CLASS'=>'this'),$_smarty_tpl->smarty,$_smarty_tpl);?>
>人民币
				<a href="<?php echo smarty_function_write_url(array('open'=>'Quote','exchange'=>'HKD'),$_smarty_tpl->smarty,$_smarty_tpl);?>
" <?php echo smarty_function_CLASS_COLOR(array('HKD'=>$_smarty_tpl->getVariable('get')->value['exchange'],'CLASS'=>'this'),$_smarty_tpl->smarty,$_smarty_tpl);?>
>港元
				<a href="<?php echo smarty_function_write_url(array('open'=>'Quote','exchange'=>'TWD'),$_smarty_tpl->smarty,$_smarty_tpl);?>
" <?php echo smarty_function_CLASS_COLOR(array('TWD'=>$_smarty_tpl->getVariable('get')->value['exchange'],'CLASS'=>'this'),$_smarty_tpl->smarty,$_smarty_tpl);?>
>台币
				<a href="<?php echo smarty_function_write_url(array('open'=>'Quote','exchange'=>'JPY'),$_smarty_tpl->smarty,$_smarty_tpl);?>
" <?php echo smarty_function_CLASS_COLOR(array('JPY'=>$_smarty_tpl->getVariable('get')->value['exchange'],'CLASS'=>'this'),$_smarty_tpl->smarty,$_smarty_tpl);?>
>日元
				<a href="<?php echo smarty_function_write_url(array('open'=>'Quote','exchange'=>'EUR'),$_smarty_tpl->smarty,$_smarty_tpl);?>
" <?php echo smarty_function_CLASS_COLOR(array('EUR'=>$_smarty_tpl->getVariable('get')->value['exchange'],'CLASS'=>'this'),$_smarty_tpl->smarty,$_smarty_tpl);?>
>欧元
				<a href="<?php echo smarty_function_write_url(array('open'=>'Quote','exchange'=>'GBP'),$_smarty_tpl->smarty,$_smarty_tpl);?>
" <?php echo smarty_function_CLASS_COLOR(array('GBP'=>$_smarty_tpl->getVariable('get')->value['exchange'],'CLASS'=>'this'),$_smarty_tpl->smarty,$_smarty_tpl);?>
>英镑

		<?php echo $_smarty_tpl->getVariable('html')->value;?>

	<?php $_template = new Smarty_Internal_Template("foot.html", $_smarty_tpl->smarty, $_smarty_tpl, $_smarty_tpl->cache_id, $_smarty_tpl->compile_id, null, null);
 echo $_template->getRenderedTemplate();?><?php $_template->updateParentVariables(0);?><?php unset($_template);?>


text:
Screw.Unit(function() {
  describe("Murmur", function() {
    var without_user_current = function(expect) {
      var backup = User.current
      try {
        User.current = function() { return null }
        expect()
      } finally {
        User.current = backup
      }
    }

    describe("a murmur can tell author info", function() {
      var m

      before(function() {
        m = new Murmur(1)
      })

      it("should be author's info if provided", function() {
        m.author({name: 'name', login: 'login', icon_path: 'author icon'})
        m.jabber_user_name("jabber")
        expect(m.author_name()).to(equal, 'name')
        expect(m.author_icon()).to(equal, 'author icon')
      })

      it("should be jabber user's info if can not get author info", function() {
        m.jabber_user_name("jabber")
        expect(m.author_name()).to(equal, 'jabber (jabber)')
        expect(m.author_icon()).to(be_null)
      })

      it("author_name should be null when both author and jabber name are absent", function() {
        expect(m.author_name()).to(be_null)
        expect(m.author_icon()).to(be_null)
      })

    })

    describe("a murmur can detect mentions", function() {
      var murmur_with_mention
      var murmur_without_mention
      before(function() {
        User.current_user = new User()
        User.current_user.name('wang pengchao')

        murmur_with_mention = new Murmur(1)
        murmur_with_mention.content('@space @bug hello there @wpc')

        murmur_without_mention = new Murmur(2)
        murmur_without_mention.content('no mention wpc')
      })

      it("when username is different case", function() {
        User.current_user.login('WpC')
        expect(murmur_with_mention.mentions_current_user()).to(equal, true)
      })

      it("when form is @login", function() {
        User.current_user.login('wpc')
        expect(murmur_with_mention.mentions_current_user()).to(equal, true)
      })

      it("unless current user can not be detected", function() {
        without_user_current(function() {
          expect(murmur_with_mention.mentions_current_user()).to(equal, false)
        })
      })

      it("unless there is no @ symbol", function() {
        User.current_user.login('wpc')
        expect(murmur_without_mention.mentions_current_user()).to(equal, false)
      })

      it("when form is @first_part_of_display_name", function() {
        User.current_user.login("mike")
        User.current_user.name("space garbage")
        expect(murmur_with_mention.mentions_current_user()).to(equal, true)
      })

      it("when form is @last_part_of_display_name", function() {
        User.current_user.login("mike")
        User.current_user.name("yucky bug")
        expect(murmur_with_mention.mentions_current_user()).to(equal, true)
      })

      it("unless they only begin with username", function() {
        User.current_user.login("wp")
        expect(murmur_with_mention.mentions_current_user()).to(equal, false)
      })

      it("when they end with a non-word character", function() {
        User.current_user.login('maleksiu')
        User.current_user.name('space baby')
        murmur_with_mention.content("@space: what's up?")
        expect(murmur_with_mention.mentions_current_user()).to(equal, true)
      })
    })

    describe("#from_current_user", function() {
      before(function() {
        User.current_user = new User()
        User.current_user.name('wang pengchao')
        User.current_user.login("wpc")
      })

      var murmur_by = function(author) {
        var m = new Murmur(1)
        m.author(author)
        return m
      }

      describe("when murmur author are same with current user", function() {
        it("is from_current_user", function() {
          expect(murmur_by({login: 'wpc'}).from_current_user()).to(be_true)
        })
      })

      describe("when murmur author are others", function() {
        it("is not from_current_user", function() {
          expect(murmur_by({login: 'mike'}).from_current_user()).to(be_false)
        })
      })

      describe("when can not decide who current user", function() {
        it("is not from_current_user", function() {
          without_user_current(function() {
            expect(murmur_by({login: 'wpc'}).from_current_user()).to(be_false)
          })
        })
      })

      describe("when murmur has no author", function() {
        it("is not from_current_user", function() {
          expect(murmur_by().from_current_user()).to(be_false)
        })
      })
    })

    describe("murmur is blank when", function() {
      it("content is null", function() {
        var murmur = new Murmur(1)
        expect(murmur.blank()).to(be_true)
      })

      it("content is empty string", function() {
        var murmur = new Murmur(1)
        murmur.content("")
        expect(murmur.blank()).to(be_true)
      })

      it("content only contain spaces", function() {
        var murmur = new Murmur(1)
        murmur.content("    ")
        expect(murmur.blank()).to(be_true)
      })

      it("content only contain cr or spaces", function() {
        var murmur = new Murmur(1)
        murmur.content("  \n  ")
        expect(murmur.blank()).to(be_true)
      })

    })

    describe("remurmur", function(){
      it("to valide author", function(){
        var murmur = new Murmur(1)
        murmur.author({login : 'phoenix'})
        murmur.content('hi')
        expect(murmur.remurmur()).to(equal, 'RM @phoenix: hi // ')
      })

      it("to valide jabber user name", function(){
        var murmur = new Murmur(1)
        murmur.jabber_user_name('phoenix')
        murmur.content('hi')
        expect(murmur.remurmur()).to(equal, 'RM @phoenix: hi // ')
      })
    })

    describe("reply", function(){
      it("valid user login", function(){
        var murmur = new Murmur(1)
        murmur.author({login : 'phoenix'})
        expect(murmur.reply()).to(equal, '@phoenix ')
      })

      it("valid user jabber user name", function(){
        var murmur = new Murmur(1)
        murmur.jabber_user_name('phoenix')
        expect(murmur.reply()).to(equal, '@phoenix ')
      })
    })

  })
})


text:
Questions?

		# ♥


text:
Chip8 emulator
==============

A chip8 emulator written in C and work under windows.

![ScreenShot](https://github.com/Gabriele91/Chip8-emulator/blob/master/chip-8.jpg?raw=true)


text:
package org.kie.server.integrationtests.jbpm.rest;

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

import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.rules.ExternalResource;
import org.kie.api.runtime.process.ProcessInstance;
import org.kie.server.client.CaseServicesClient;
import org.kie.server.client.KieServicesClient;
import org.kie.server.client.ProcessServicesClient;
import org.kie.server.client.QueryServicesClient;
import org.kie.server.integrationtests.jbpm.DBExternalResource;
import org.kie.server.integrationtests.shared.basetests.RestOnlyBaseIntegrationTest;

public abstract class RestJbpmBaseIntegrationTest extends RestOnlyBaseIntegrationTest {

    @ClassRule
    public static ExternalResource StaticResource = new DBExternalResource();

    protected static final String USER_YODA = "yoda";
    protected static final String USER_JOHN = "john";

    protected ProcessServicesClient processClient;
    protected QueryServicesClient queryClient;
    protected CaseServicesClient caseClient;

    @Before
    public void cleanup() {
        cleanupSingletonSessionId();
    }

    @After
    public void abortAllProcesses() {
        List<Integer> status = new ArrayList<Integer>();
        status.add(ProcessInstance.STATE_ACTIVE);
        List<org.kie.server.api.model.instance.ProcessInstance> activeInstances = queryClient.findProcessInstancesByStatus(status, 0, 100);
        if (activeInstances != null) {
            for (org.kie.server.api.model.instance.ProcessInstance instance : activeInstances) {
                processClient.abortProcessInstance(instance.getContainerId(), instance.getId());
            }
        }
    }

    @Override
    protected void setupClients(KieServicesClient client) {
        processClient = client.getServicesClient(ProcessServicesClient.class);
        queryClient = client.getServicesClient(QueryServicesClient.class);
        caseClient = client.getServicesClient(CaseServicesClient.class);
    }
}


text:
package laraifox.foxtail.physics.collision;

public interface ICollider2D {
	public Collision collides(ICollider2D other);
}


text:
try:
    from .asset import *
except ImportError:
    # requirements-extras are missing
    pass


text:
package com.buterfleoge.whale;

import org.apache.commons.lang.builder.ReflectionToStringBuilder;
import org.apache.commons.lang.builder.ToStringStyle;

/**
 * 覆盖toString方法
 *
 * @author xiezhenzong
 *
 */
public abstract class BaseObject {

    @Override
    public String toString() {
        return ReflectionToStringBuilder.toString(this, ToStringStyle.SHORT_PREFIX_STYLE);
    }

}


text:
class CXFA_Level final : public CXFA_Node {
 public:
  CXFA_Level(CXFA_Document* doc, XFA_PacketType packet);
  ~CXFA_Level() override;
};

#endif  // XFA_FXFA_PARSER_CXFA_LEVEL_H_


text:
SYNONYM

#### According to
Index Fungorum

#### Published in
null

#### Original name
Phyllachora quercae A.K. Kar & S.K. Gupta

### Remarks
null


text:
'use strict';

var _ = require('lodash');
var Collection = require('../Collection');

var assert = require('assert');
var matchNode = require('../matchNode');
var recast = require('recast');

var Node = recast.types.namedTypes.Node;
var types = recast.types.namedTypes;

function methodNameFromType(type) {
  return 'visit' + type;
}

function functionify(value) {
  return typeof value === 'function' ? value : function() {
    return value;
  };
}

var traversalMethods = {

  /**
   * Find nodes of a specific type within the nodes of this collection.
   *
   * @param {type}
   * @param {filter}
   * @return {Collection}
   */
  find: function(type, filter) {
    var paths = [];
    var visitorMethodName = methodNameFromType(type);

    var visitor = {};
    function visit(path) {
      /*jshint validthis:true */
      if (!filter || matchNode(path.value, filter)) {
        paths.push(path);
      }
      this.traverse(path);
    }
    this.__paths.forEach(function(p, i) {
      var self = this;
      visitor[visitorMethodName] = function(path) {
        if (self.__paths[i] === path) {
          this.traverse(path);
        } else {
          return visit.call(this, path);
        }
      };
      recast.visit(p, visitor);
    }, this);

    return Collection.fromPaths(paths, this, type);
  },

  /**
   * Returns a collection containing the paths that create the scope of the
   * currently selected paths. Dedupes the paths.
   *
   * @return {Collection}
   */
  closestScope: function() {
    return this.map(path => path.scope && path.scope.path);
  },

  /**
   * Traverse the AST up and finds the closest node of the provided type.
   *
   * @param {Collection}
   * @param {filter}
   * @return {Collection}
   */
  closest: function(type, filter) {
    return this.map(function(path) {
      var parent = path.parent;
      while (
        parent &&
        !type.check(parent.value) &&
        (!filter || matchNode(parent.value, filter))
      ) {
        parent = parent.parent;
      }
      return parent || null;
    });
  },

  /**
   * Finds the declaration for each selected path. Useful for member expressions
   * or JSXElements. Expects a callback function that maps each path to the name
   * to look for.
   *
   * If the callback returns a falsey value, the element is skipped.
   *
   * @param {function} nameGetter
   *
   * @return {Collection}
   */
  getVariableDeclarators: function(nameGetter) {
    return this.map(function(path) {
      /*jshint curly:false*/
      var scope = path.scope;
      if (!scope) return;
      var name = nameGetter.apply(path, arguments);
      if (!name) return;
      scope = scope.lookup(name);
      if (!scope) return;
      var bindings = scope.getBindings()[name];
      if (!bindings) return;
      var decl = Collection.fromPaths(bindings)
        .closest(types.VariableDeclarator);
      if (decl.size() === 1) {
        return decl.paths()[0];
      }
    }, types.VariableDeclarator);
  },
};

var mutationMethods = {
  /**
   * Simply replaces the selected nodes with the provided node. If a function
   * is provided it is executed for every node and the node is replaced with the
   * functions return value.
   *
   * @param {Node|function} replacement
   * @return {Collection}
   */
  replaceWith: function(replacement) {
    replacement = functionify(replacement);

    return this.forEach(function(path, i) {
      var newNode = replacement.call(path, path, i);
      assert(Node.check(newNode), 'Replacement function returns a node');
      path.replace(newNode);
    });
  },

  /**
   * Inserts a new node before the current one.
   *
   * @param {Node|function} insert
   * @return {Collection}
   */
  insertBefore: function(insert) {
    insert = functionify(insert);

    return this.forEach(function(path, i) {
      var node = insert.call(path, path, i);
      assert(Node.check(node), 'Insert function returns a node');
      path.insertBefore(node);
    });
  },

  /**
   * Inserts a new node after the current one.
   *
   * @param {Node|function} insert
   * @return {Collection}
   */
  insertAfter: function(insert) {
    insert = functionify(insert);

    return this.forEach(function(path, i) {
      var node = insert.call(path, path, i);
      assert(Node.check(node), 'Insert function returns a node');
      path.insertAfter(node);
    });
  }

};

function register() {
  Collection.registerMethods(traversalMethods, Node);
  Collection.registerMethods(mutationMethods, Node);
  Collection.setDefaultCollectionType(Node);
}

exports.register = _.once(register);


text:
using Microsoft.Silverlight.Testing;
using Microsoft.Silverlight.Testing.Client;
using System.Windows;
using System.Windows.Controls;

namespace DevExpress {
    class TestGrid : Grid, ITestPage {
        ITestPage TestPage { get; set; }
        public Panel TestPanel {
            get { return TestPage.TestPanel; }
        }
        public TestGrid(ComboBox comboBox, ITestPage testPage) {
            TestPage = testPage;
            RowDefinitions.Add(new RowDefinition() { Height = GridLength.Auto });
            RowDefinitions.Add(new RowDefinition());
            if(comboBox != null) {
                Children.Add(comboBox);
                comboBox.SetValue(Grid.RowProperty, 0);
            }
            Children.Add((UIElement)testPage);
            ((UIElement)testPage).SetValue(Grid.RowProperty, 1);
        }
    }
}


text:
package template

import (
	"path/filepath"

	"context"

	. "github.com/dave/jennifer/jen"
	mstrings "github.com/devimteam/microgen/generator/strings"
	"github.com/devimteam/microgen/generator/write_strategy"
)

const (
	nameInterruptHandler = "InterruptHandler"
	nameMain             = "main"
	nameInitLogger       = "InitLogger"
	nameServeGRPC        = "ServeGRPC"
	nameServeHTTP        = "ServeHTTP"
)

const (
	_service_ = "svc"
	_logger_  = "logger"
	_ctx_     = "ctx"
)

type mainTemplate struct {
	Info     *GenerationInfo
	rendered []string
	state    WriteStrategyState
}

func NewMainTemplate(info *GenerationInfo) Template {
	return &mainTemplate{
		Info: info,
	}
}

func (t *mainTemplate) Render(ctx context.Context) write_strategy.Renderer {
	f := &Statement{}
	f.Line().Add(t.mainFunc(ctx))
	f.Line().Add(t.initLogger())
	f.Line().Add(t.interruptHandler())
	f.Line().Add(t.serveGrpc(ctx))
	f.Line().Add(t.serveHTTP(ctx))

	if t.state == AppendStrat {
		return f
	}

	file := NewFile("main")
	file.PackageComment(`Microgen appends missed functions.`)
	file.Add(f)

	return file
}

func (t *mainTemplate) DefaultPath() string {
	return filepath.Join("./", PathExecutable, mstrings.ToSnakeCase(t.Info.Iface.Name), "/main.go")
}

func (t *mainTemplate) Prepare(ctx context.Context) error {
	return nil
}

func (t *mainTemplate) ChooseStrategy(ctx context.Context) (write_strategy.Strategy, error) {
	return write_strategy.NewCreateFileStrategy(t.Info.OutputFilePath, t.DefaultPath()), nil
	/*if err := statFile(t.Info.OutputFilePath, t.DefaultPath()); os.IsNotExist(err) {
		t.state = FileStrat
		return write_strategy.NewCreateFileStrategy(t.Info.OutputFilePath, t.DefaultPath()), nil
	}
	file, err := parsePackage(filepath.Join(t.Info.OutputFilePath, t.DefaultPath()))
	if err != nil {
		logger.Logger.Logln(0, "can't parse", t.DefaultPath(), ":", err)
		return write_strategy.NewNopStrategy("", ""), nil
	}
	for _, f := range file.Functions {
		t.rendered = append(t.rendered, f.Name)
	}
	t.state = AppendStrat
	return write_strategy.NewAppendToFileStrategy(t.Info.OutputFilePath, t.DefaultPath()), nil*/
}

func (t *mainTemplate) interruptHandler() *Statement {
	if mstrings.IsInStringSlice(nameInterruptHandler, t.rendered) {
		return nil
	}
	s := &Statement{}
	s.Comment(nameInterruptHandler + ` handles first SIGINT and SIGTERM and returns it as error.`).Line()
	s.Func().Id(nameInterruptHandler).Params(ctx_contextContext).Params(Error()).Block(
		Id("interruptHandler").Op(":=").Id("make").Call(Id("chan").Qual(PackagePathOs, "Signal"), Lit(1)),
		Qual(PackagePathOsSignal, "Notify").Call(
			Id("interruptHandler"),
			Qual(PackagePathSyscall, "SIGINT"),
			Qual(PackagePathSyscall, "SIGTERM"),
		),
		Select().Block(
			Case(Id("sig").Op(":= <-").Id("interruptHandler")),
			Return().Qual(PackagePathFmt, "Errorf").Call(Lit("signal received: %v"), Id("sig").Dot("String").Call()),
			Case(Op("<-").Id(_ctx_).Dot("Done").Call()),
			Return().Qual(PackagePathErrors, "New").Call(Lit("signal listener: context canceled")),
		),
	)
	return s
}

func (t *mainTemplate) mainFunc(ctx context.Context) *Statement {
	if mstrings.IsInStringSlice(nameMain, t.rendered) {
		return nil
	}
	return Func().Id(nameMain).Call().BlockFunc(func(main *Group) {
		main.Id(_logger_).Op(":=").
			Qual(PackagePathGoKitLog, "With").Call(Id(nameInitLogger).Call(Qual(PackagePathOs, "Stdout")), Lit("level"), Lit("info"))
		if Tags(ctx).Has(RecoveringMiddlewareTag) {
			main.Id("errorLogger").Op(":=").
				Qual(PackagePathGoKitLog, "With").Call(Id(nameInitLogger).Call(Qual(PackagePathOs, "Stderr")), Lit("level"), Lit("error"))
		}
		main.Id(_logger_).Dot("Log").Call(Lit("message"), Lit("Hello, I am alive"))
		main.Defer().Id(_logger_).Dot("Log").Call(Lit("message"), Lit("goodbye, good luck"))
		main.Line()
		main.List(Id("g"), Id(_ctx_)).Op(":=").Qual(PackagePathSyncErrgroup, "WithContext").Call(Qual(PackagePathContext, "Background").Call())
		main.Id("g").Dot("Go").Call(
			Func().Params().Params(Error()).Block(
				Return().Id(nameInterruptHandler).Call(Id(_ctx_)),
			),
		)
		main.Line()
		main.Var().Id(_service_).Qual(t.Info.SourcePackageImport, t.Info.Iface.Name).Comment("// TODO:").Op("=").Qual(t.Info.OutputPackageImport+"/service", constructorName(t.Info.Iface)).Call().
			Comment(`Create new service.`)
		//if Tags(ctx).Has(CachingMiddlewareTag) {
		//	main.Id(_service_).Op("=").
		//		Qual(filepath.Join(t.Info.SourcePackageImport, PathService), CachingMiddlewareName).Call(Id("errorLogger")).Call(Id(_service_)).
		//		Comment(`Setup service caching.`)
		//}
		if Tags(ctx).Has(LoggingMiddlewareTag) {
			main.Id(_service_).Op("=").
				Qual(filepath.Join(t.Info.OutputPackageImport, PathService), ServiceLoggingMiddlewareName).Call(Id(_logger_)).Call(Id(_service_)).
				Comment(`Setup service logging.`)
		}
		if Tags(ctx).Has(ErrorLoggingMiddlewareTag) {
			main.Id(_service_).Op("=").
				Qual(filepath.Join(t.Info.OutputPackageImport, PathService), ServiceErrorLoggingMiddlewareName).Call(Id(_logger_)).Call(Id(_service_)).
				Comment(`Setup error logging.`)
		}
		if Tags(ctx).Has(RecoveringMiddlewareTag) {
			main.Id(_service_).Op("=").
				Qual(filepath.Join(t.Info.OutputPackageImport, PathService), ServiceRecoveringMiddlewareName).Call(Id("errorLogger")).Call(Id(_service_)).
				Comment(`Setup service recovering.`)
		}
		main.Line().Id("endpoints").Op(":=").Qual(t.Info.OutputPackageImport+"/transport", "Endpoints").Call(t.endpointsParams(ctx))
		if Tags(ctx).HasAny(TracingMiddlewareTag) {
			main.Id("endpoints").Op("=").Qual(t.Info.OutputPackageImport+"/transport", "TraceServerEndpoints").Call(
				Id("endpoints"),
				Qual(PackagePathOpenTracingGo, "NoopTracer{}"),
			).Comment("TODO: Add tracer")
		}
		if Tags(ctx).HasAny(GrpcTag, GrpcServerTag) {
			main.Line()
			main.Id("grpcAddr").Op(":=").Lit(":8081").Comment("TODO: use normal address")
			main.Comment(`Start grpc server.`)
			main.Id("g").Dot("Go").Call(
				Func().Params().Params(Error()).Block(
					Return().Id(nameServeGRPC).Call(
						Id(_ctx_),
						Op("&").Id("endpoints"),
						Id("grpcAddr"),
						Qual(PackagePathGoKitLog, "With").Call(Id(_logger_), Lit("transport"), Lit("GRPC")),
					),
				),
			)
		}
		if Tags(ctx).HasAny(HttpTag, HttpServerTag) {
			main.Line()
			main.Id("httpAddr").Op(":=").Lit(":8080").Comment("TODO: use normal address")
			main.Comment(`Start http server.`)
			main.Id("g").Dot("Go").Call(
				Func().Params().Params(Error()).Block(
					Return().Id(nameServeHTTP).Call(
						Id(_ctx_),
						Op("&").Id("endpoints"),
						Id("httpAddr"),
						Qual(PackagePathGoKitLog, "With").Call(Id(_logger_), Lit("transport"), Lit("HTTP")),
					),
				),
			)
		}
		main.Line()
		main.If(Err().Op(":=").Id("g").Dot("Wait").Call(), Err().Op("!=").Nil()).Block(
			Id(_logger_).Dot("Log").Call(Lit("error"), Err()),
		)
	})
}

// Renders something like this
//		func InitLogger(writer io.Writer) log.Logger {
//			logger := log.NewJSONLogger(writer)
//			logger = log.With(logger, "@timestamp", log.DefaultTimestampUTC)
//			logger = log.With(logger, "caller", log.DefaultCaller)
//			return logger
//		}
func (t *mainTemplate) initLogger() *Statement {
	if mstrings.IsInStringSlice(nameInitLogger, t.rendered) {
		return nil
	}
	return Comment(nameInitLogger + ` initialize go-kit JSON logger with timestamp and caller.`).Line().
		Func().Id(nameInitLogger).Params(Id("writer").Qual(PackagePathIO, "Writer")).Params(Qual(PackagePathGoKitLog, "Logger")).BlockFunc(func(body *Group) {
		body.Id(_logger_).Op(":=").Qual(PackagePathGoKitLog, "NewJSONLogger").Call(Id("writer"))
		body.Id(_logger_).Op("=").Qual(PackagePathGoKitLog, "With").Call(Id(_logger_), Lit("@timestamp"), Qual(PackagePathGoKitLog, "DefaultTimestampUTC"))
		body.Id(_logger_).Op("=").Qual(PackagePathGoKitLog, "With").Call(Id(_logger_), Lit("caller"), Qual(PackagePathGoKitLog, "DefaultCaller"))
		body.Return(Id(_logger_))
	})
}

// Renders something like this
//		func serveGRPC(endpoints *clientsvc.Endpoints, errCh chan error) {
// 			logger := log.With(logger, "transport", "grpc")
// 			listener, err := net.Listen("tcp", *bindAddr)
// 			if err != nil {
// 				errCh <- err
// 				return
// 			}
//
// 			srv := transportgrpc.NewGRPCServer(endpoints)
// 			grpcs := grpc.NewServer()
// 			pb.RegisterClientServiceServer(grpcs, srv)
//
// 			logger.Log("addr", *bindAddr)
// 			errCh <- grpcs.Serve(listener)
// 		}
func (t *mainTemplate) serveGrpc(ctx context.Context) *Statement {
	if !Tags(ctx).HasAny(GrpcTag, GrpcServerTag) || mstrings.IsInStringSlice(nameServeGRPC, t.rendered) {
		return nil
	}
	return Comment(nameServeGRPC+` starts new GRPC server on address and sends first error to channel.`).Line().
		Func().Id(nameServeGRPC).Params(
		ctx_contextContext,
		Id("endpoints").Op("*").Qual(filepath.Join(t.Info.OutputPackageImport, "transport"), EndpointsSetName),
		Id("addr").Id("string"),
		Id(_logger_).Qual(PackagePathGoKitLog, "Logger"),
	).Params(
		Error(),
	).BlockFunc(func(body *Group) {
		body.List(Id("listener"), Err()).Op(":=").Qual(PackagePathNet, "Listen").Call(Lit("tcp"), Id("addr"))
		body.If(Err().Op("!=").Nil()).Block(
			Return().Err(),
		)
		body.Comment(`Here you can add middlewares for grpc server.`)
		body.Id("server").Op(":=").Qual(filepath.Join(t.Info.OutputPackageImport, "transport/grpc"), "NewGRPCServer").Call(t.newServerParams(ctx))
		body.Id("grpcServer").Op(":=").Qual(PackagePathGoogleGRPC, "NewServer").Call()
		body.Qual(t.Info.ProtobufPackageImport, "Register"+mstrings.ToUpperFirst(t.Info.Iface.Name)+"Server").Call(Id("grpcServer"), Id("server"))
		body.Id(_logger_).Dot("Log").Call(Lit("listen on"), Id("addr"))
		body.Id("ch").Op(":=").Make(Id("chan error"))
		body.Go().Func().Call().Block(
			Id("ch").Op("<-").Id("grpcServer").Dot("Serve").Call(Id("listener")),
		).Call()
		body.Select().Block(
			Case(Err().Op(":= <-").Id("ch")),
			Return().Qual(PackagePathFmt, "Errorf").Call(Lit("grpc server: serve: %v"), Err()),
			Case(Op("<-").Id(_ctx_).Dot("Done").Call()),
			Id("grpcServer").Dot("GracefulStop").Call(),
			Return().Qual(PackagePathErrors, "New").Call(Lit("grpc server: context canceled")),
		)
	})
}

func (t *mainTemplate) serveHTTP(ctx context.Context) *Statement {
	if !Tags(ctx).HasAny(HttpTag, HttpServerTag) || mstrings.IsInStringSlice(nameServeHTTP, t.rendered) {
		return nil
	}
	return Comment(nameServeHTTP+` starts new HTTP server on address and sends first error to channel.`).Line().
		Func().Id(nameServeHTTP).Params(
		ctx_contextContext,
		Id("endpoints").Op("*").Qual(t.Info.OutputPackageImport+"/transport", EndpointsSetName),
		Id("addr").Id("string"),
		Id(_logger_).Qual(PackagePathGoKitLog, "Logger"),
	).Params(
		Error(),
	).BlockFunc(func(body *Group) {
		body.Id("handler").Op(":=").Qual(t.Info.OutputPackageImport+"/transport/http", "NewHTTPHandler").Call(t.newServerParams(ctx))
		body.Id("httpServer").Op(":=").Op("&").Qual(PackagePathHttp, "Server").Values(DictFunc(func(d Dict) {
			d[Id("Addr")] = Id("addr")
			d[Id("Handler")] = Id("handler")
		}))
		body.Id(_logger_).Dot("Log").Call(Lit("listen on"), Id("addr"))
		body.Id("ch").Op(":=").Make(Id("chan error"))
		body.Go().Func().Call().Block(
			Id("ch").Op("<-").Id("httpServer").Dot("ListenAndServe").Call(),
		).Call()
		body.Select().Block(
			Case(Err().Op(":= <-").Id("ch")),
			If(Err().Op("==").Qual(PackagePathHttp, "ErrServerClosed")).Block(
				Return().Nil(),
			),
			Return().Qual(PackagePathFmt, "Errorf").Call(Lit("http server: serve: %v"), Err()),
			Case(Op("<-").Id(_ctx_).Dot("Done").Call()),
			Return().Id("httpServer").Dot("Shutdown").Call(Qual(PackagePathContext, "Background").Call()),
		)
	})
}

func (t *mainTemplate) endpointsParams(ctx context.Context) *Statement {
	s := &Statement{}
	s.Id(_service_)
	/*if Tags(ctx).HasAny(TracingMiddlewareTag) {
		s.Op(",").Line().Qual(PackagePathOpenTracingGo, "NoopTracer{}").Op(",").Comment("TODO: Add tracer").Line()
	}*/
	return s
}

func (t *mainTemplate) newServerParams(ctx context.Context) *Statement {
	s := &Statement{}
	s.Id("endpoints")
	if Tags(ctx).HasAny(TracingMiddlewareTag) {
		s.Op(",").Line().Id(_logger_)
	}
	if Tags(ctx).HasAny(TracingMiddlewareTag) {
		s.Op(",").Line().Qual(PackagePathOpenTracingGo, "NoopTracer{}").Op(",").Comment("TODO: Add tracer").Line()
	}
	return s
}


text:
using System;
using System.Collections;
using System.IO;
using System.Windows.Ink;
using MS.Internal.IO.Packaging;

namespace MS.Internal.Ink.InkSerializedFormat
{
    /// <summary>
    /// Summary description for GuidTagList.
    /// </summary>
    internal class GuidList
    {
        private System.Collections.Generic.List<Guid> _CustomGuids = new System.Collections.Generic.List<Guid>();

        public GuidList()
        {
        }

        /// <summary>
        /// Adds a guid to the list of Custom Guids if it is not a known guid and is already not
        /// in the list of Custom Guids
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public bool Add(Guid guid)
        {
            // If the guid is not found in the known guids list nor in the custom guid list,
            // add that to the custom guid list
            if (0 == FindTag(guid, true))
            {
                _CustomGuids.Add(guid);
                return true;
            }
            else
                return false;
        }

        /// <summary>
        /// Finds the tag for a Guid based on the list of Known Guids
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static KnownTagCache.KnownTagIndex FindKnownTag(Guid guid)
        {
            // Find out if the guid is in the known guid table
            for (byte iIndex = 0; iIndex < KnownIdCache.OriginalISFIdTable.Length; ++iIndex)
                if (guid == KnownIdCache.OriginalISFIdTable[iIndex])
                    return KnownIdCache.KnownGuidBaseIndex + iIndex;

            // Couldnt find in the known list
            return 0;
        }

        /// <summary>
        /// Finds the tag for a guid based on the list of Custom Guids
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        KnownTagCache.KnownTagIndex FindCustomTag(Guid guid)
        {
            int i;

            for (i = 0; i < _CustomGuids.Count; i++)
            {
                if (guid.Equals(_CustomGuids[i]))
                    return (KnownTagCache.KnownTagIndex)(KnownIdCache.CustomGuidBaseIndex + i);
            }

            return KnownTagCache.KnownTagIndex.Unknown;
        }

        /// <summary>
        /// Finds a tag corresponding to a guids
        /// </summary>
        /// <param name="guid"></param>
        /// <param name="bFindInKnownListFirst"></param>
        /// <returns></returns>
        public KnownTagCache.KnownTagIndex FindTag(Guid guid, bool bFindInKnownListFirst)
        {
            KnownTagCache.KnownTagIndex tag = KnownTagCache.KnownTagIndex.Unknown;

            if (bFindInKnownListFirst)
            {
                tag = FindKnownTag(guid);
                if (KnownTagCache.KnownTagIndex.Unknown == tag)
                    tag = FindCustomTag(guid);
            }
            else
            {
                tag = FindCustomTag(guid);
                if (KnownTagCache.KnownTagIndex.Unknown == tag)
                    tag = FindKnownTag(guid);
            }

            return tag;
        }

        /// <summary>
        /// Finds a known guid based on a Tag
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        static Guid FindKnownGuid(KnownTagCache.KnownTagIndex tag)
        {
            if (tag < KnownIdCache.KnownGuidBaseIndex)
            {
                throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("Tag is outside of the known guid tag range"));
            }

            // Get the index in the OriginalISFIdTable array first
            uint nIndex = (uint)(tag - KnownIdCache.KnownGuidBaseIndex);

            // If invalid, return Guid.Empty
            if (KnownIdCache.OriginalISFIdTable.Length <= nIndex)
                return Guid.Empty;

            // Otherwise, return the guid
            return KnownIdCache.OriginalISFIdTable[nIndex];
        }

        /// <summary>
        /// Finds a Custom Guid based on a Tag
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        Guid FindCustomGuid(KnownTagCache.KnownTagIndex tag)
        {
            if ((int)tag < (int)KnownIdCache.CustomGuidBaseIndex)
            {
                throw new ArgumentException(StrokeCollectionSerializer.ISFDebugMessage("Tag is outside of the known guid tag range"));
            }

            // Get the index in the OriginalISFIdTable array first
            int nIndex = (int)(tag - KnownIdCache.CustomGuidBaseIndex);

            // If invalid, return Guid.Empty
            if ((0 > nIndex) || (_CustomGuids.Count <= nIndex))
                return Guid.Empty;

            // Otherwise, return the guid
            return (Guid)_CustomGuids[(int)nIndex];
        }

        /// <summary>
        /// Finds a guid based on Tag
        /// </summary>
        /// <param name="tag"></param>
        /// <returns></returns>
        public Guid FindGuid(KnownTagCache.KnownTagIndex tag)
        {
            if (tag < (KnownTagCache.KnownTagIndex)KnownIdCache.CustomGuidBaseIndex)
            {
                Guid guid = FindKnownGuid(tag);

                if (Guid.Empty != guid)
                    return guid;

                return FindCustomGuid(tag);
            }
            else
            {
                Guid guid = FindCustomGuid(tag);

                if (Guid.Empty != guid)
                    return guid;

                return FindKnownGuid(tag);
            }
        }

        /// <summary>
        /// Returns the expected size of data if it is a known guid
        /// </summary>
        /// <param name="guid"></param>
        /// <returns></returns>
        public static uint GetDataSizeIfKnownGuid(Guid guid)
        {
            for (uint i = 0; i < KnownIdCache.OriginalISFIdTable.Length; ++i)
            {
                if (guid == KnownIdCache.OriginalISFIdTable[i])
                {
                    return KnownIdCache.OriginalISFIdPersistenceSize[i];
                }
            }

            return 0;
        }

        /// <summary>
        /// Serializes the GuidList in the memory stream and returns the size
        /// </summary>
        /// <param name="stream">If null, calculates the size only</param>
        /// <returns></returns>
        public uint Save(Stream stream)
        {
                // calculate the number of custom guids to persist
                //   custom guids are those which are not reserved in ISF via 'tags'
            uint ul = (uint)(_CustomGuids.Count * Native.SizeOfGuid);

                // if there are no custom guids, then the guid list can be persisted
                //      without any cost ('tags' are freely storeable)
            if (ul == 0)
            {
                return 0;
            }

                // if only the size was requested, return it
            if (null == stream)
            {
                return (uint)(ul + SerializationHelper.VarSize(ul) + SerializationHelper.VarSize((uint)KnownTagCache.KnownTagIndex.GuidTable));
            }

                // encode the guid table tag in the output stream
            uint cbWrote = SerializationHelper.Encode(stream, (uint)KnownTagCache.KnownTagIndex.GuidTable);

                // encode the size of the guid table
            cbWrote += SerializationHelper.Encode(stream, ul);

                // encode each guid in the table
            for (int i = 0; i < _CustomGuids.Count; i++)
            {
                Guid guid = (Guid)_CustomGuids[i];

                stream.Write(guid.ToByteArray(), 0, (int)Native.SizeOfGuid);
            }

            cbWrote += ul;
            return cbWrote;
        }

        /// <summary>
        /// Deserializes the GuidList from the memory stream
        /// </summary>
        /// <param name="strm"></param>
        /// <param name="size"></param>
        /// <returns></returns>
        public uint Load(Stream strm, uint size)
        {
            uint cbsize = 0;

            _CustomGuids.Clear();

            uint count = size / Native.SizeOfGuid;
            byte[] guids = new byte[Native.SizeOfGuid];

            for (uint i = 0; i < count; i++)
            {
                // NTRAID:WINDOWSOS#1622775-2006/04/26-WAYNEZEN,
                // Stream.Read could read less number of bytes than the request. We call ReliableRead that
                // reads the bytes in a loop until all requested bytes are received or reach the end of the stream.
                uint bytesRead = StrokeCollectionSerializer.ReliableRead(strm, guids, Native.SizeOfGuid);

                cbsize += bytesRead;
                if ( bytesRead == Native.SizeOfGuid )
                {
                    _CustomGuids.Add(new Guid(guids));
                }
                else
                {
                    // If Stream.Read cannot return the expected number of bytes, we should break here.
                    // The caller - StrokeCollectionSerializer.DecodeRawISF will check our return value.
                    // An exception might be thrown if reading is failed.
                    break;
                }
            }

            return cbsize;
        }
    }
}


text:
import React from 'react'

import './styles.css'

const Documents = ({ documentSummary }) => {
  if (!(documentSummary && documentSummary.summary)) {
    return null
  }
  return (

1. flutningsmaður

            {documentSummary.summary.bills.presenter.count}

Frumvörp

            {documentSummary.summary.motions.presenter.count}

Þingsályktunartillögur

Meðflutningsmaður

            {documentSummary.summary.motions.coPresenter.count}

Frumvörp

            {documentSummary.summary.motions.coPresenter.count}

Þingsályktunartillögur

Fyrirspurnir

            {documentSummary.summary.inquiries.asked}

Spurningar

            {documentSummary.summary.inquiries.answered}

Svör

  )
}

Documents.propTypes = {}

export default Documents


text:
package com.thoughtworks.selenium;

import org.testng.ITestContext;
import org.testng.TestRunner;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.AfterTest;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.BeforeSuite;
import org.testng.annotations.BeforeTest;
import org.testng.annotations.Optional;
import org.testng.annotations.Parameters;
import org.testng.internal.IResultListener;

import java.io.File;
import java.lang.reflect.Method;

public class SeleneseTestNgHelper extends SeleneseTestBase {

  private static Selenium staticSelenium;

  @BeforeTest
  @Override
  @Parameters({"selenium.url", "selenium.browser"})
  public void setUp(@Optional String url, @Optional String browserString) throws Exception {
    if (browserString == null) {
      browserString = runtimeBrowserString();
    }
    super.setUp(url, browserString);
    staticSelenium = selenium;
  }

  @BeforeClass
  @Parameters({"selenium.restartSession"})
  public void getSelenium(@Optional("false") boolean restartSession) {
    selenium = staticSelenium;
    if (restartSession) {
      selenium.stop();
      selenium.start();
    }
  }

  @BeforeMethod
  public void setTestContext(Method method) {
    selenium.setContext(
        method.getDeclaringClass().getSimpleName() + "." + method.getName());

  }

  @BeforeSuite
  @Parameters({"selenium.host", "selenium.port"})
  public void attachScreenshotListener(@Optional("localhost") String host,
      @Optional("4444") String port, ITestContext context) {
    if (!"localhost".equals(host)) {
      return;
    }
    Selenium screenshotTaker = new DefaultSelenium(host, Integer.parseInt(port),
        "", "");
    TestRunner tr = (TestRunner) context;
    File outputDirectory = new File(context.getOutputDirectory());
    tr.addListener((IResultListener) new ScreenshotListener(outputDirectory,
        screenshotTaker));
  }

  @AfterMethod
  @Override
  public void checkForVerificationErrors() {
    super.checkForVerificationErrors();
  }

  @AfterMethod(alwaysRun = true)
  public void selectDefaultWindow() {
    if (selenium != null) {
      selenium.selectWindow("null");
    }
  }

  @AfterTest(alwaysRun = true)
  @Override
  public void tearDown() throws Exception {
    super.tearDown();
  }

  // @Override static method of super class (which assumes JUnit conventions)
  public static void assertEquals(Object actual, Object expected) {
    SeleneseTestBase.assertEquals(expected, actual);
  }

  // @Override static method of super class (which assumes JUnit conventions)
  public static void assertEquals(String actual, String expected) {
    SeleneseTestBase.assertEquals(expected, actual);
  }

  // @Override static method of super class (which assumes JUnit conventions)
  public static void assertEquals(String actual, String[] expected) {
    SeleneseTestBase.assertEquals(expected, actual);
  }

  // @Override static method of super class (which assumes JUnit conventions)
  public static void assertEquals(String[] actual, String[] expected) {
    SeleneseTestBase.assertEquals(expected, actual);
  }

  // @Override static method of super class (which assumes JUnit conventions)
  public static boolean seleniumEquals(Object actual, Object expected) {
    return SeleneseTestBase.seleniumEquals(expected, actual);
  }

  // @Override static method of super class (which assumes JUnit conventions)
  public static boolean seleniumEquals(String actual, String expected) {
    return SeleneseTestBase.seleniumEquals(expected, actual);
  }

  @Override
  public void verifyEquals(Object actual, Object expected) {
    super.verifyEquals(expected, actual);
  }

  @Override
  public void verifyEquals(String[] actual, String[] expected) {
    super.verifyEquals(expected, actual);
  }
}


text:
require 'rails_helper'

describe PaperTrail::VersionDecorator, fast: true, versioning: true do
  describe '#pretty_item_type' do
    context 'item is a project' do
      it 'should return Project' do
        project = create :project
        expect(project.versions.first.decorate.pretty_item_type).to eq 'Project'
      end
    end

    context 'item is a data table' do
      it 'should return Table' do
        project = create :project
        project.data_tables << create(:data_table)
        expect(
          project.data_tables.first.versions.first.decorate.pretty_item_type
        ).to eq 'Table'
      end
    end

    context 'item is Analyzable Vector' do
      it 'should return Row' do
        project = create :project
        project.data_tables << create(:data_table)
        project.data_tables.first.rows << create(:row)
        expect(
          project.data_tables.first.rows.first.versions.last.decorate.pretty_item_type
        ).to eq 'Row'
      end
    end

    context 'item is Generic File' do
      it 'should return File' do
        project = create :project
        project.generic_files << create(:generic_file)
        expect(
          project.generic_files.first.versions.first.decorate.pretty_item_type
        ).to eq 'File'
      end
    end
  end

  describe '#pretty_whodunnit' do
    context 'user is defined' do
      it 'should return the user name' do
        user = create :site_user
        version = PaperTrail::Version.new whodunnit: user.id
        expect(version.decorate.pretty_whodunnit).to eq user.user_name
      end
    end

    context 'user is not defined' do
      it 'should return system' do
        version = PaperTrail::Version.new
        expect(version.decorate.pretty_whodunnit).to eq 'System'
      end
    end
  end

  describe '#format_changeset' do
    let(:data_table) do
      create :data_table,
             name: 'name',
             description: 'some words',
             access_level: 0
    end

    before(:each) do
      data_table.name = 'new_name'
      data_table.description = 'foo'
      data_table.access_level = 2
      data_table.save
    end

    context 'ascii format' do
      context 'created version' do
        it 'should format the diff' do
          new_data_table = create :data_table, name: 'foo'
          expect(
            new_data_table.versions.last.decorate.format_changeset(
              format: :ascii
            )
          ).to include 'name: {+"foo"}'
        end
      end
      context 'edited versions' do
        it 'should format the diff' do
          expect(
            data_table.versions.last.decorate.format_changeset(format: :ascii)
          ).to include 'name: {"name" >> "new_name"}'
        end
      end
    end

    context 'html format' do
      it 'should format the diff' do
        expect(
          data_table.decorate.format_changeset(
            data_table.versions.last.changeset, format: :html
          )
        ).to include 'name: ' \
                'namenew_name'
      end
    end
  end # describe 'format_changeset'
end