text:
/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package pl.edu.mimuw.dmexlib_rseslib.pso_reducts;

import java.io.File;
import java.io.IOException;
import java.util.Map;
import java.util.Properties;
import pl.edu.mimuw.dmexlib.nodes.operations.pso.ICostFunction;
import pl.edu.mimuw.dmexlib_rseslib.data_views.DoubleDataTableView;
import pl.edu.mimuw.dmexlib_rseslib.data_views.HeaderView;
import rseslib.processing.classification.ClassifierSet;
import rseslib.processing.classification.CrossValidationTest;
import rseslib.processing.classification.MultipleTestResult;
import rseslib.processing.classification.rules.roughset.RoughSetRuleClassifier;
import rseslib.structure.attribute.formats.HeaderFormatException;
import rseslib.structure.data.formats.DataFormatException;
import rseslib.structure.table.ArrayListDoubleDataTable;
import rseslib.structure.table.DoubleDataTable;
import rseslib.system.PropertyConfigurationException;
import rseslib.system.progress.EmptyProgress;

/**
 *
 * @author Mateusz
 */
public class Cost implements ICostFunction<FitnessValue, Position> {

    private final String CLASSIFIER_NAME = "GReducts";

    public Cost(String fileName) throws PropertyConfigurationException, IOException, HeaderFormatException, DataFormatException, InterruptedException {
        File dataFile = new File(fileName);
        this.table = new ArrayListDoubleDataTable(dataFile, new EmptyProgress());
    }

    @Override
    public FitnessValue evaluate(Position p) {
        final double alpha = 0.9;
        final double beta = 0.1;

        final double length = (p.dimensions() - p.cardinality()) / p.dimensions();
        final double acc = accuracy(p);

        updateStats(p.cardinality(), acc);

        return new FitnessValue(alpha * acc + beta * length, acc);
    }

    public int noOfAttr() {
        return table.attributes().noOfAttr();
    }

    public int getMinLength() {
        return minLength;
    }

    public int getMaxLength() {
        return maxLength;
    }

    public double getMinAccuracy() {
        return minAccuracy;
    }

    public double getMaxAccuracy() {
        return maxAccuracy;
    }

    private double accuracy(Position p) {
        try {
            final Properties testProp = new Properties();
            final ClassifierSet classifiers = new ClassifierSet();

            testProp.setProperty(CrossValidationTest.NO_OF_FOLDS_PROPERTY_NAME, "10");
            testProp.setProperty(RoughSetRuleClassifier.s_sRuleGenerator, "GlobalReducts");

            classifiers.addClassifier(CLASSIFIER_NAME, RoughSetRuleClassifier.class);

            // Create table with some columns filtered out
            HeaderView head = new HeaderView(table.attributes(), p.mapping());
            DoubleDataTable posTable = new DoubleDataTableView(table, head);

            // Do cross-cvalidation test
            CrossValidationTest crossValid = new CrossValidationTest(testProp, classifiers);
            Map<String, MultipleTestResult> results = crossValid.test(posTable, new EmptyProgress());

            return results.get(CLASSIFIER_NAME).getAverage();// Create table with some columns filtered out
        } catch (PropertyConfigurationException ex) {
            return 0.0;
        } catch (InterruptedException ex) {
            return 0.0;
        }
    }

    private void updateStats(int length, double accuracy) {
        minLength = Math.min(length, minLength);
        maxLength = Math.max(length, maxLength);
        minAccuracy = Math.min(accuracy, minAccuracy);
        maxAccuracy = Math.max(accuracy, maxAccuracy);
    }

    private final DoubleDataTable table;
    private int minLength = Integer.MAX_VALUE;
    private int maxLength = Integer.MIN_VALUE;
    private double minAccuracy = Double.MAX_VALUE;
    private double maxAccuracy = Double.MIN_VALUE;

}


text:
require.ensure([], function(require) {
require("./5.async.js");
require("./11.async.js");
require("./22.async.js");
require("./43.async.js");
});
module.exports = 44;

redpajama_set_name: RedPajamaGithub


text:
#ifndef _RSA_HELPER_
#define _RSA_HELPER_
#include <linux/mpi.h>

struct rsa_key {
	MPI n;
	MPI e;
	MPI d;
};

int rsa_parse_pub_key(struct rsa_key *rsa_key, const void *key,
		      unsigned int key_len);

int rsa_parse_priv_key(struct rsa_key *rsa_key, const void *key,
		       unsigned int key_len);

void rsa_free_key(struct rsa_key *rsa_key);

extern struct crypto_template rsa_pkcs1pad_tmpl;
#endif


text:
"""
.. dialect:: postgresql+pygresql
    :name: pygresql
    :dbapi: pgdb
    :connectstring: postgresql+pygresql://user:password@host:port/dbname[?key=value&key=value...]
    :url: https://www.pygresql.org/

.. note::

    The pygresql dialect is **not tested as part of SQLAlchemy's continuous
    integration** and may have unresolved issues.  The recommended PostgreSQL
    dialect is psycopg2.

.. deprecated:: 1.4 The pygresql DBAPI is deprecated and will be removed
   in a future version. Please use one of the supported DBAPIs to
   connect to PostgreSQL.

"""  # noqa

import decimal
import re

from .base import _DECIMAL_TYPES
from .base import _FLOAT_TYPES
from .base import _INT_TYPES
from .base import PGCompiler
from .base import PGDialect
from .base import PGIdentifierPreparer
from .base import UUID
from .hstore import HSTORE
from .json import JSON
from .json import JSONB
from ... import exc
from ... import processors
from ... import util
from ...sql.elements import Null
from ...types import JSON as Json
from ...types import Numeric

class _PGNumeric(Numeric):
    def bind_processor(self, dialect):
        return None

    def result_processor(self, dialect, coltype):
        if not isinstance(coltype, int):
            coltype = coltype.oid
        if self.asdecimal:
            if coltype in _FLOAT_TYPES:
                return processors.to_decimal_processor_factory(
                    decimal.Decimal, self._effective_decimal_return_scale
                )
            elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES:
                # PyGreSQL returns Decimal natively for 1700 (numeric)
                return None
            else:
                raise exc.InvalidRequestError(
                    "Unknown PG numeric type: %d" % coltype
                )
        else:
            if coltype in _FLOAT_TYPES:
                # PyGreSQL returns float natively for 701 (float8)
                return None
            elif coltype in _DECIMAL_TYPES or coltype in _INT_TYPES:
                return processors.to_float
            else:
                raise exc.InvalidRequestError(
                    "Unknown PG numeric type: %d" % coltype
                )

class _PGHStore(HSTORE):
    def bind_processor(self, dialect):
        if not dialect.has_native_hstore:
            return super(_PGHStore, self).bind_processor(dialect)
        hstore = dialect.dbapi.Hstore

        def process(value):
            if isinstance(value, dict):
                return hstore(value)
            return value

        return process

    def result_processor(self, dialect, coltype):
        if not dialect.has_native_hstore:
            return super(_PGHStore, self).result_processor(dialect, coltype)

class _PGJSON(JSON):
    def bind_processor(self, dialect):
        if not dialect.has_native_json:
            return super(_PGJSON, self).bind_processor(dialect)
        json = dialect.dbapi.Json

        def process(value):
            if value is self.NULL:
                value = None
            elif isinstance(value, Null) or (
                value is None and self.none_as_null
            ):
                return None
            if value is None or isinstance(value, (dict, list)):
                return json(value)
            return value

        return process

    def result_processor(self, dialect, coltype):
        if not dialect.has_native_json:
            return super(_PGJSON, self).result_processor(dialect, coltype)

class _PGJSONB(JSONB):
    def bind_processor(self, dialect):
        if not dialect.has_native_json:
            return super(_PGJSONB, self).bind_processor(dialect)
        json = dialect.dbapi.Json

        def process(value):
            if value is self.NULL:
                value = None
            elif isinstance(value, Null) or (
                value is None and self.none_as_null
            ):
                return None
            if value is None or isinstance(value, (dict, list)):
                return json(value)
            return value

        return process

    def result_processor(self, dialect, coltype):
        if not dialect.has_native_json:
            return super(_PGJSONB, self).result_processor(dialect, coltype)

class _PGUUID(UUID):
    def bind_processor(self, dialect):
        if not dialect.has_native_uuid:
            return super(_PGUUID, self).bind_processor(dialect)
        uuid = dialect.dbapi.Uuid

        def process(value):
            if value is None:
                return None
            if isinstance(value, (str, bytes)):
                if len(value) == 16:
                    return uuid(bytes=value)
                return uuid(value)
            if isinstance(value, int):
                return uuid(int=value)
            return value

        return process

    def result_processor(self, dialect, coltype):
        if not dialect.has_native_uuid:
            return super(_PGUUID, self).result_processor(dialect, coltype)
        if not self.as_uuid:

            def process(value):
                if value is not None:
                    return str(value)

            return process

class _PGCompiler(PGCompiler):
    def visit_mod_binary(self, binary, operator, **kw):
        return (
            self.process(binary.left, **kw)
            + " %% "
            + self.process(binary.right, **kw)
        )

    def post_process_text(self, text):
        return text.replace("%", "%%")

class _PGIdentifierPreparer(PGIdentifierPreparer):
    def _escape_identifier(self, value):
        value = value.replace(self.escape_quote, self.escape_to_quote)
        return value.replace("%", "%%")

class PGDialect_pygresql(PGDialect):

    driver = "pygresql"
    supports_statement_cache = True

    statement_compiler = _PGCompiler
    preparer = _PGIdentifierPreparer

    @classmethod
    def dbapi(cls):
        import pgdb

        util.warn_deprecated(
            "The pygresql DBAPI is deprecated and will be removed "
            "in a future version. Please use one of the supported DBAPIs to "
            "connect to PostgreSQL.",
            version="1.4",
        )

        return pgdb

    colspecs = util.update_copy(
        PGDialect.colspecs,
        {
            Numeric: _PGNumeric,
            HSTORE: _PGHStore,
            Json: _PGJSON,
            JSON: _PGJSON,
            JSONB: _PGJSONB,
            UUID: _PGUUID,
        },
    )

    def __init__(self, **kwargs):
        super(PGDialect_pygresql, self).__init__(**kwargs)
        try:
            version = self.dbapi.version
            m = re.match(r"(\d+)\.(\d+)", version)
            version = (int(m.group(1)), int(m.group(2)))
        except (AttributeError, ValueError, TypeError):
            version = (0, 0)
        self.dbapi_version = version
        if version < (5, 0):
            has_native_hstore = has_native_json = has_native_uuid = False
            if version != (0, 0):
                util.warn(
                    "PyGreSQL is only fully supported by SQLAlchemy"
                    " since version 5.0."
                )
        else:
            self.supports_unicode_statements = True
            self.supports_unicode_binds = True
            has_native_hstore = has_native_json = has_native_uuid = True
        self.has_native_hstore = has_native_hstore
        self.has_native_json = has_native_json
        self.has_native_uuid = has_native_uuid

    def create_connect_args(self, url):
        opts = url.translate_connect_args(username="user")
        if "port" in opts:
            opts["host"] = "%s:%s" % (
                opts.get("host", "").rsplit(":", 1)[0],
                opts.pop("port"),
            )
        opts.update(url.query)
        return [], opts

    def is_disconnect(self, e, connection, cursor):
        if isinstance(e, self.dbapi.Error):
            if not connection:
                return False
            try:
                connection = connection.connection
            except AttributeError:
                pass
            else:
                if not connection:
                    return False
            try:
                return connection.closed
            except AttributeError:  # PyGreSQL < 5.0
                return connection._cnx is None
        return False

dialect = PGDialect_pygresql


text:
#include <jni.h>
#include <v8.h>

#include "AndroidUtil.h"
#include "EventEmitter.h"
#include "TypeConverter.h"
#include "V8Util.h"
#include "JNIUtil.h"
#include "V8Runtime.h"

#define TAG "EventEmitter"

using namespace v8;

namespace titanium {

Persistent<FunctionTemplate> EventEmitter::constructorTemplate;

static Persistent<String> eventsSymbol;
Persistent<String> EventEmitter::emitSymbol;

void EventEmitter::eventEmitterConstructor(const FunctionCallbackInfo<Value>& args)
{
	HandleScope scope(args.GetIsolate());
	EventEmitter *emitter = new EventEmitter();
	emitter->Wrap(args.This());
}

void EventEmitter::initTemplate(Local<Context> context)
{
	Isolate* isolate = context->GetIsolate();
	HandleScope scope(isolate);
	Local<FunctionTemplate> constructor = FunctionTemplate::New(isolate, eventEmitterConstructor);
	constructor->InstanceTemplate()->SetInternalFieldCount(1);
	constructor->SetClassName(NEW_SYMBOL(isolate, "EventEmitter"));
	constructorTemplate.Reset(isolate, constructor);

	eventsSymbol.Reset(isolate, NEW_SYMBOL(isolate, "_events"));
	emitSymbol.Reset(isolate, NEW_SYMBOL(isolate, "emit"));
}

void EventEmitter::dispose()
{
	constructorTemplate.Reset();
	eventsSymbol.Reset();
	emitSymbol.Reset();
}

bool EventEmitter::emit(Local<String> event, int argc, Local<Value> *argv)
{
	Isolate* isolate = Isolate::GetCurrent();
	HandleScope scope(isolate);

	Local<Object> self = handle();

	Local<Value> events_v = self->Get(eventsSymbol.Get(isolate));
	if (!events_v->IsObject()) return false;

	Local<Object> events = events_v.As<Object>();

	Local<Value> listeners_v = events->Get(event);
	TryCatch try_catch;

	if (listeners_v->IsFunction()) {
		// Optimized one-listener case
		Local<Function> listener = listeners_v.As<Function>();
		listener->Call(isolate->GetCurrentContext(), self, argc, argv);
		if (try_catch.HasCaught()) {
			V8Util::fatalException(isolate, try_catch);
			return false;
		}
	} else if (listeners_v->IsArray()) {
		Local<Array> listeners = listeners_v.As<Array>()->Clone().As<Array>();
		for (uint32_t i = 0; i < listeners->Length(); ++i) {
			Local<Value> listener_v = listeners->Get(i);
			if (!listener_v->IsFunction()) continue;
			Local<Function> listener = listener_v.As<Function>();
			listener->Call(isolate->GetCurrentContext(), self, argc, argv);
			if (try_catch.HasCaught()) {
				V8Util::fatalException(isolate, try_catch);
				return false;
			}
		}
	} else {
		return false;
	}

	return true;
}

} // namespace titanium


text:
<?xml version="1.0" encoding="utf-8"?>
<Rules FriendlyName="Custom Rules">
	<Rule TypeName="HelloWorldRule" Category="CustomRules" CheckId="CR1000">
		<Name>Demo Rule</Name>
		<Description>I am an example of a custom FxCop rule</Description>
		<Url></Url>
		<Resolution>This method name starts with the letter 'C': {0}. There's no resolution because ain't nothin' wrong wit dat.</Resolution>
		<MessageLevel Certainty="0">Error</MessageLevel>
		<Email></Email>
		<FixCategories>DependsOnFix</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="SkipAuthorizeRule" Category="CustomRules" CheckId="CR1001">
		<Name>Controllers/Actions with Skip Authorize Attribute</Name>
		<Description>This controller/action skips authorization and can be accessed without a login.</Description>
		<Url></Url>
		<Resolution>Check to make sure this is desired. Very few pages should skip authorization - the login page, the external website, etc.</Resolution>
		<MessageLevel Certainty="30">Error</MessageLevel>
		<Email></Email>
		<FixCategories>DependsOnFix</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="SuspiciousGetRequestsRule" Category="CustomRules" CheckId="CR1002">
		<Name>Actions that allow HttpGet, but appear to alter data</Name>
		<Description>This action allows HttpGet requests, but its name indicates that it may be altering data (or it calls a function that appears to alter data).</Description>
		<Url></Url>
		<Resolution>The method '{0}' matches keyword{1}. If the action indeed changes data, make sure it only accepts HttpPost requests. If it doesn't, consider renaming it.</Resolution>
		<MessageLevel Certainty="75">Error</MessageLevel>
		<Email></Email>
		<FixCategories>DependsOnFix</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="SQLInjectionRule" Category="CustomRules" CheckId="CR1013">
		<Name>Potential SQL injection</Name>
		<Description>Using a 'dirty' string as a SQL command. This string has been concatenated with the method parameters or other strings of unknown origins.</Description>
		<Url></Url>
		<Resolution>Dirty variable: {0} marked dirty at: {1} Review for possible SQL injection. Ideally, consider using parameterized queries or a stored procedure instead of dynamic SQL. Otherwise, ensure that the input is sanitized (no single quotes if it's a string, semicolons otherwise) and/or that it's always coming from a trustworthy source.</Resolution>
		<MessageLevel Certainty="25">Warning</MessageLevel>
		<Email></Email>
		<FixCategories>DependsOnFix</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="MissingRoleCheckRule" Category="CustomRules" CheckId="CR1004">
		<Name>Controllers missing AccessDeniedAuthorizeAttribute</Name>
		<Description>This controller/action can be accessed by any user.</Description>
		<Url></Url>
		<Resolution>Check to make sure this is desired. Some pages should require elevated permissions / specific roles.</Resolution>
		<MessageLevel Certainty="20">Warning</MessageLevel>
		<Email></Email>
		<FixCategories>DependsOnFix</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="UnloggedEmailRule" Category="CustomRules" CheckId="CR1005">
		<Name>Emails sent using the unlogged email function</Name>
		<Description>CDS.Core.Utils isn't able to do data access - these emails will go unlogged.</Description>
		<Url></Url>
		<Resolution>You almost certainly want to use CDS.Web.Email.SendLoggedMail.</Resolution>
		<MessageLevel Certainty="80">Error</MessageLevel>
		<Email></Email>
		<FixCategories>NonBreaking</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="JSONAllowGetRule" Category="CustomRules" CheckId="CR1007">
		<Name>JSON AllowGet</Name>
		<Description>This JSON result may allow HttpGet requests.</Description>
		<Url></Url>
		<Resolution>JSON requests are often modifying user data, displaying users' private data, or performing actions. If it's doing anything other than returning non-private data, it shouldn't allow GETs.</Resolution>
		<MessageLevel Certainty="50">Warning</MessageLevel>
		<Email></Email>
		<FixCategories>DependsOnFix</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="MissingHttpMethodRule" Category="CustomRules" CheckId="CR1008">
		<Name>Missing HTTP Method Attribute</Name>
		<Description>This Action doesn't specify HttpGet or HttpPost.</Description>
		<Url></Url>
		<Resolution>Allow only POST for any actions that may alter data. Requests that GET data are safe to accept POSTS, but they're worth reviewing.</Resolution>
		<MessageLevel Certainty="10">Warning</MessageLevel>
		<Email></Email>
		<FixCategories>DependsOnFix</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="UnloggedThreadingRule" Category="CustomRules" CheckId="CR1009">
		<Name>Background threads started without using CDS.Threading</Name>
		<Description>Background threads don't contain state (for example, the HttpContext). Errors on a background thread will not be tied back to the original web request or user.</Description>
		<Url></Url>
		<Resolution>You almost certainly want to use CDS.Threading.TaskFactory.StartNew().</Resolution>
		<MessageLevel Certainty="70">Error</MessageLevel>
		<Email></Email>
		<FixCategories>NonBreaking</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="XSSRule" Category="CustomRules" CheckId="CR1010">
		<Name>Review functions for XSS vulnerabilities</Name>
		<Description>Built-in MVC HTML functions (except for Html.Raw, of course) automatically HTML encode potentially dangerous strings, preventing the injection of script tags. Any function we write should be reviewed to ensure that it properly escapes HTML.</Description>
		<Url></Url>
		<Resolution>Make sure this function properly escapes HTML tags.</Resolution>
		<MessageLevel Certainty="20">Warning</MessageLevel>
		<Email></Email>
		<FixCategories>NonBreaking</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="StaticDisposableRule" Category="CustomRules" CheckId="CR1011">
		<Name>IDisposable types used as static fields</Name>
		<Description>IDisposable classes are inteded to be disposed when they're no longer in use, and typically have state that is not thread safe. You may be misusing a context across multiple threads by declaring one as static, or you may be maintaining an instance in memory unnecessarily.</Description>
		<Url></Url>
		<Resolution>If the class has context that doesnt't apply across the entire application (this includes EntityFramework's ObjectContext), change this to an instance field. Consider whther this object should be in memory perpetually.</Resolution>
		<MessageLevel Certainty="70">Error</MessageLevel>
		<Email></Email>
		<FixCategories>Breaking</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="ContextInDataDLLRule" Category="CustomRules" CheckId="CR1012">
		<Name>Accessing a .Current context instance in a data DLL</Name>
		<Description>If this function's results are ever cached, the contextual inputs will be missing from the cache key, leading to improper cache collision. If this function is ever used in a remoting situation, this context will not be available at all.</Description>
		<Url></Url>
		<Resolution>Pass whatever components of the context '{0}' are needed as method parameters.</Resolution>
		<MessageLevel Certainty="90">Error</MessageLevel>
		<Email></Email>
		<FixCategories>Breaking</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
	<Rule TypeName="SafeSqlBuilderRule" Category="CustomRules" CheckId="CR1014">
		<Name>SafeSQLBuilder not acutally safe.</Name>
		<Description>This type is labeled as a safe SQL builder but it's doing something shady.</Description>
		<Url></Url>
		<Resolution>If you're accepting strings from user input, or from the database, it's not safe. Use constants, literals, and parameters to build your dynamic SQL, yo! Or stop labeling it as 'safe'.</Resolution>
		<MessageLevel Certainty="90">Error</MessageLevel>
		<Email></Email>
		<FixCategories>Breaking</FixCategories>
		<Owner>Chris Shaffer</Owner>
	</Rule>
</Rules>


text:
<?php
namespace Concrete\Core\Database\EntityManager\Driver;

use Concrete\Core\Application\Application;
use Concrete\Core\Config\Repository\Repository;
use Doctrine\ORM\Mapping\Driver\AnnotationDriver;
use Doctrine\ORM\Mapping\Driver\XmlDriver;
use Doctrine\ORM\Mapping\Driver\YamlDriver;

class ApplicationDriver implements DriverInterface
{

    /**
     * @var Application
     */
    protected $app;

    /**
     * @var Repository
     */
    protected $config;

    /**
     * Constructor
     *
     * @param Repository $config
     * @param Application $app
     */
    public function __construct(Repository $config, Application $app)
    {
        $this->app = $app;
        $this->config = $config;
    }

    /**
     * Does support legacy namespace with src
     *
     * @return bool
     */
    private function isLegacy()
    {
        return $this->config->get('app.enable_legacy_src_namespace');
    }

    /**
     * Return the correct MappingDriver base on the application config
     *
     * @return XmlDriver|YamlDriver|AnnotationDriver
     */
    public function getDriver()
    {
        $config = $this->config;
        if ($this->isLegacy()) {
            $appEntityPath = DIR_APPLICATION . '/' . DIRNAME_CLASSES;
            $reader = $this->app->make('orm/cachedSimpleAnnotationReader');
        } else {
            $appEntityPath = DIR_APPLICATION . '/' . DIRNAME_CLASSES . '/' . DIRNAME_ENTITIES;
            $reader = $this->app->make('orm/cachedAnnotationReader');
        }

        $appDriverSettings = $config->get(CONFIG_ORM_METADATA_APPLICATION);
        $xmlConfig = DIR_APPLICATION . '/' . REL_DIR_METADATA_XML;
        $ymlConfig = DIR_APPLICATION . '/' . REL_DIR_METADATA_YAML;

        // Default setting so it comes first
        if (empty($appDriverSettings) && is_dir($appEntityPath)) {
            return new AnnotationDriver($reader, $appEntityPath);
        } else {
            if ($appDriverSettings === 'xml') {
                if (is_dir($xmlConfig)) {
                    return new XmlDriver($xmlConfig);
                } else {
                    // Fallback to default
                    return new AnnotationDriver($reader, $appEntityPath);
                }
            } else {
                if ($appDriverSettings === 'yaml' || $appDriverSettings === 'yml') {
                    if (is_dir($ymlConfig)) {
                        return new YamlDriver($ymlConfig);
                    } else {
                        // Fallback to default
                        return new AnnotationDriver($reader, $appEntityPath);
                    }
                }
            }
        }
    }

    /**
     * Get eather the default application namespace,
     * or the legacy appliation namespace
     *
     * @return string
     */
    public function getNamespace()
    {
        if ($this->isLegacy()) {
            return 'Application\Src';
        } else {
            return 'Application\Entity';
        }
    }
}


text:
<?php
if ( ! function_exists( 'add_filter' ) ) {
	exit;
}

if ( ! defined( 'HOCWP_PLUGIN_CORE_VERSION' ) ) {
	define( 'HOCWP_PLUGIN_CORE_VERSION', '2.0.0' );
}

class HOCWP_Plugin {
	public $name;
	public $version;
	public $file;
	public $path;
	public $url;
	public $inc_path;
	public $custom_path;
	public $basename;
	public $dirname;
	public $option_name;
	public $setting_url;
	public $use_session;
	public $option_defaults;
	public $license_data;
	public $textdomain;
	public $load_core_scripts;
	public $admin_menu_parent = 'hocwp_plugin_option';

	public function __construct() {
		$this->init();
		$this->pre_hook();
		$this->load();
		$this->hook();
	}

	private function init() {
		$this->path        = untrailingslashit( plugin_dir_path( $this->file ) );
		$this->url         = plugins_url( '', $this->file );
		$this->inc_path    = $this->path . '/inc';
		$this->custom_path = $this->path . '/custom';
		$this->basename    = plugin_basename( $this->file );
		$this->dirname     = dirname( $this->basename );
		if ( ! empty( $this->option_name ) ) {
			$this->setting_url = admin_url( 'admin.php?page=' . $this->option_name );
		}
	}

	private function pre_hook() {
		add_filter( 'hocwp_compress_paths', array( $this, 'minify_file_path' ) );
		$this->option_defaults   = apply_filters( $this->name . '_option_defaults', $this->option_defaults );
		$this->load_core_scripts = apply_filters( $this->name . '_load_core_scripts', $this->load_core_scripts );
	}

	private function hook() {
		if ( $this->use_session ) {
			add_action( 'init', 'hocwp_session_start' );
		}
		register_activation_hook( $this->file, array( $this, 'activation' ) );
		register_deactivation_hook( $this->file, array( $this, 'deactivation' ) );
		add_action( 'hocwp_check_license', array( $this, 'check_license' ) );
		add_filter( 'plugin_action_links_' . $this->basename, array( $this, 'settings_link' ) );
		add_action( 'plugins_loaded', array( $this, 'load_textdomain' ) );
		add_action( 'admin_init', array( $this, 'admin_init' ) );
		if ( ! is_admin() ) {
			add_action( 'admin_bar_menu', array( $this, 'admin_bar_menu' ), 99 );
		}
		add_action( 'wp_enqueue_scripts', array( $this, 'enqueue_scripts' ) );
		add_action( 'admin_enqueue_scripts', array( $this, 'admin_enqueue_scripts' ) );
		add_filter( 'body_class', array( $this, 'body_class' ) );
		if ( ! is_admin() ) {
			add_action( 'admin_bar_menu', array( $this, 'admin_bar_menu_front_end' ), 99 );
		}
	}

	public function admin_bar_menu_front_end( $wp_admin_bar ) {

	}

	public function body_class( $classes ) {
		if ( ! $this->license_valid() ) {
			$classes[] = 'hocwp-invalid-license';
		}

		return $classes;
	}

	public function enqueue_scripts() {
		hocwp_register_core_style_and_script();
		$localize_object = hocwp_default_script_localize_object();
		if ( hocwp_is_debugging() ) {
			wp_localize_script( 'hocwp', 'hocwp', $localize_object );
			wp_register_script( 'hocwp-front-end', HOCWP_URL . '/js/hocwp-front-end' . HOCWP_JS_SUFFIX, array( 'hocwp' ), false, true );
			wp_register_script( $this->textdomain, $this->url . '/js/hocwp-plugin' . HOCWP_JS_SUFFIX, array( 'hocwp-front-end' ), false, true );
		} else {
			wp_register_script( $this->textdomain, $this->url . '/js/hocwp-plugin' . HOCWP_JS_SUFFIX, array(), $this->version, true );
			wp_localize_script( $this->textdomain, 'hocwp', $localize_object );
		}
		wp_register_style( $this->textdomain . '-style', $this->url . '/css/hocwp-plugin' . HOCWP_CSS_SUFFIX, array(), $this->version );
		wp_enqueue_style( $this->textdomain . '-style' );
		$script = apply_filters( $this->name . '_use_scripts', true );
		if ( $script ) {
			wp_enqueue_script( $this->textdomain );
		}
	}

	public function admin_enqueue_scripts() {
		hocwp_register_core_style_and_script();
		hocwp_admin_enqueue_scripts();
		wp_register_style( 'hocwp-admin-style', HOCWP_URL . '/css/hocwp-admin' . HOCWP_CSS_SUFFIX, array( 'hocwp-style' ), $this->version );
		wp_register_script( 'hocwp-admin', HOCWP_URL . '/js/hocwp-admin' . HOCWP_JS_SUFFIX, array(
			'jquery',
			'hocwp'
		), $this->version, true );
		wp_register_style( $this->textdomain . '-style', $this->url . '/css/hocwp-plugin-admin' . HOCWP_CSS_SUFFIX, array( 'hocwp-admin-style' ), $this->version );
		wp_register_script( $this->textdomain, $this->url . '/js/hocwp-plugin-admin' . HOCWP_JS_SUFFIX, array( 'hocwp-admin' ), $this->version, true );
		wp_localize_script( $this->textdomain, 'hocwp', hocwp_default_script_localize_object() );
		wp_enqueue_style( $this->textdomain . '-style' );
		wp_enqueue_script( $this->textdomain );
	}

	public function check_license() {
		if ( ! isset( $_POST['submit'] ) && ! hocwp_is_login_page() ) {
			if ( ! $this->license_valid() && ! HOCWP_DOING_CRON && ! HOCWP_DOING_AJAX && ! HOCWP_DOING_AUTO_SAVE ) {
				if ( ! is_admin() && current_user_can( 'manage_options' ) ) {
					wp_redirect( HOCWP_PLUGIN_LICENSE_ADMIN_URL );
					exit;
				}
				add_action( 'admin_notices', array( $this, 'invalid_license_notice' ) );
			}
		}
	}

	final function admin_bar_menu( $wp_admin_bar ) {
		$args = array(
			'id'     => 'plugin-license',
			'title'  => __( 'Plugin Licenses', 'hocwp-theme' ),
			'href'   => HOCWP_PLUGIN_LICENSE_ADMIN_URL,
			'parent' => 'plugins'
		);
		$wp_admin_bar->add_node( $args );
	}

	public function invalid_license_notice() {
		$plugin_name = hocwp_get_plugin_name( $this->file, $this->basename );
		$plugin_name = hocwp_wrap_tag( $plugin_name, 'strong' );
		$args        = array(
			'error' => true,
			'title' => __( 'Error', 'hocwp-theme' ),
			'text'  => sprintf( __( 'Plugin %1$s is using an invalid license key! If you does not have one, please contact %2$s via email address %3$s for more information.', 'hocwp-theme' ), $plugin_name, '' . HOCWP_NAME . '', '' . HOCWP_EMAIL . '' )
		);
		hocwp_admin_notice( $args );
	}

	public function get_license_data() {
		$data = apply_filters( $this->name . '_license_defined_data', $this->license_data, $this );

		return $data;
	}

	public function minify_file_path( $paths ) {
		if ( ! is_array( $paths ) ) {
			$paths = array();
		}
		$paths[] = $this->path;

		return $paths;
	}

	public function load() {
		require( $this->custom_path . '/hocwp-plugin-pre-hook.php' );

		require_once( HOCWP_PATH . '/plugin-functions.php' );

		require_once( HOCWP_PATH . '/options/plugin-option.php' );

		require( $this->inc_path . '/setup-plugin.php' );
	}

	public function get_option() {
		$defaults = $this->option_defaults;
		$option   = get_option( $this->option_name );
		if ( ! hocwp_array_has_value( $option ) ) {
			$option = array();
		}
		$option = wp_parse_args( $option, $defaults );

		return apply_filters( $this->option_name . '_options', $option );
	}

	public function license_data() {
		$data = array(
			'hashed'  => '',
			'key_map' => '',
			'domain'  => ''
		);

		return $data;
	}

	public function license_valid() {
		$license = new HOCWP_License();
		$license->set_type( 'plugin' );
		$license->set_use_for( $this->basename );
		$license->set_option_name( 'hocwp_plugin_license' );
		$data = $this->license_data;
		if ( ! hocwp_array_has_value( $data ) ) {
			$data = $this->license_data();
		}
		$result = $license->check_valid( $data );
		unset( $license );

		return $result;
	}

	public function activation() {
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}
		flush_rewrite_rules();
		do_action( $this->name . '_activation' );
	}

	public function deactivation() {
		if ( ! current_user_can( 'activate_plugins' ) ) {
			return;
		}
		flush_rewrite_rules();
		do_action( $this->name . '_deactivation' );
	}

	final function settings_link( $links ) {
		if ( ! empty( $this->setting_url ) ) {
			$settings_link = sprintf( 'setting_url . '">%s', __( 'Settings', 'hocwp-theme' ) );
			array_unshift( $links, $settings_link );
		}

		return $links;
	}

	final function load_textdomain() {
		load_plugin_textdomain( $this->textdomain, false, $this->path . '/languages/' );
	}

	final function admin_init() {
		$plugin_base_name = md5( $this->basename );
		$option_name      = 'plugin_' . $plugin_base_name . '_version';
		$version          = get_option( $option_name );
		if ( $version != $this->version ) {
			update_option( $option_name, $this->version );
			flush_rewrite_rules();
		}
	}

	final function add_option_to_sidebar_tab( HOCWP_Option $option ) {
		if ( ! hocwp_menu_page_exists( $this->option_name ) ) {
			global $hocwp_pos_tabs;
			$option->set_parent_slug( $this->admin_menu_parent );
			$option->add_option_tab( $hocwp_pos_tabs );
			$option->set_page_header_callback( 'hocwp_plugin_option_page_header' );
			$option->set_page_footer_callback( 'hocwp_plugin_option_page_footer' );
			$option->set_page_sidebar_callback( 'hocwp_plugin_option_page_sidebar' );
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:orientation="horizontal"
              android:layout_width="@dimen/smithy_item_width"
              android:layout_height="@dimen/smithy_item_height"
    android:gravity="center">

    <ImageView
        android:id="@+id/smithy_item_image"
        android:layout_width="@dimen/item_iamge_wh"
        android:layout_height="@dimen/item_iamge_wh"
        android:src="@mipmap/mine_launcher"
        android:layout_marginRight="@dimen/smithy_item_margin"/>
    <View
        android:layout_width="@dimen/item_diversion_width"
        android:layout_height="@dimen/item_diversion_height"
        android:background="@color/colorBlack"
        android:layout_gravity="center"/>
    <TextView
        android:id="@+id/smithy_item_title"
        android:layout_width="@dimen/item_title_width"
        android:layout_height="wrap_content"
        android:layout_gravity="right|center_vertical"
        android:text="器皿"
        android:gravity="center"
        android:layout_marginLeft="@dimen/smithy_item_margin"
        android:textColor="@color/colorBlack"/>

</LinearLayout>


text:
This is module is a simple hack to allow old `require.paths` deprecated method.

## Install

`$ npm install node-path`

## Usage

```javascript
// On process.mainModule; eg: node index.js
require('node-path')(module, ['../libs', '../vendor']);

// On a child module
require('node-path')(module);

var myLib = require('my-lib-in-libs');
var myVendor = require('my-vendor-in-vendors');
```

## Todo

* Add some tests
* Improve extend method

## Licence

MIT


text:
package org.cidrz.webapp.dynasite.utils;

import org.cidrz.webapp.dynasite.utils.sort.DisplayOrderComparator;
import org.cidrz.webapp.dynasite.valueobject.PageItem;

import java.util.*;

/**
 * This is a TreeSet so it will keep any sorts that the list throws at it...
 * @author Chris Kelley
 *         Date: Jun 17, 2005
 *         Time: 9:06:31 PM
 */
public class DataStructureUtils {
    private static DisplayOrderComparator c;

    /**
     * Note that this is for items such as fields that use display order.
     * @param list
     * @return Sorted set
     */
    public static final Set listToSet(List list) {
        // Declare a Set parameterized with the same type as the input List
        Set set = new TreeSet(new DisplayOrderComparator());
        // Loop over the list using regular for-loop
        // (using "for (T t : list)" breaks the compiler
        for (int i = 0; i < list.size(); i++) {
            Object o = list.get(i);
            // Add each member of the list into the set
            // (Set semantics dispose of duplicates)
            set.add(o);
        }
        return set;
    }

    public static final Set listToSet(List list, Comparator c) {

    // Declare a Set parameterized with the same type as the input List
        // c = new DisplayOrderComparator();
        Set set = new TreeSet(c);

    // Loop over the list using regular for-loop
    // (using "for (T t : list)" breaks the compiler
    for (int i=0;i<list.size();i++) {

        // Add each member of the list into the set
        // (Set semantics dispose of duplicates)
        set.add(list.get(i));
    }

    return set;
  }

    public static final Set listToSetNoComparator(List list) {

    // Declare a Set parameterized with the same type as the input List
    Set set = new HashSet();

    // Loop over the list using regular for-loop
    // (using "for (T t : list)" breaks the compiler
    for (int i=0;i<list.size();i++) {

        // Add each member of the list into the set
        // (Set semantics dispose of duplicates)
        set.add(list.get(i));
    }

    return set;
  }

    public static void createPageItem(PageItem pageItem) {
        PageItem newPageItem = new PageItem();
        newPageItem.setFormId(pageItem.getFormId());
        newPageItem.setForm_field(pageItem.getForm_field());
        newPageItem.setFormFieldId(pageItem.getFormFieldId());
        newPageItem.setInputType(pageItem.getInputType());
        newPageItem.setVisible(pageItem.isVisible());
        newPageItem.setDisplayOrder(pageItem.getDisplayOrder());
        newPageItem.setCols(pageItem.getCols());
        newPageItem.setColspan(pageItem.getColspan());
        newPageItem.setMaxlength(pageItem.getMaxlength());
        newPageItem.setSize(pageItem.getSize());
        newPageItem.setRows(pageItem.getRows());
        newPageItem.setCols(pageItem.getCols());
        newPageItem.setColumnNumber(pageItem.getColumnNumber());
        newPageItem.setColspan(pageItem.getColspan());
        newPageItem.setCloseRow(pageItem.isCloseRow());
        newPageItem.setVisibleDependencies1(pageItem.getVisibleDependencies1());
        newPageItem.setVisibleDependencies2(pageItem.getVisibleDependencies2());
        newPageItem.setVisibleEnumIdTrigger1(pageItem.getVisibleEnumIdTrigger1());
        newPageItem.setVisibleEnumIdTrigger2(pageItem.getVisibleEnumIdTrigger2());
        newPageItem.setAuditInfo(pageItem.getAuditInfo());
        newPageItem.setSelectedEnum(pageItem.getSelectedEnum());
    }
}


text:
package tabletserver

import (
	"fmt"
	"sync"
	"time"

	"vitess.io/vitess/go/vt/proto/vtrpc"
	"vitess.io/vitess/go/vt/vterrors"

	"golang.org/x/net/context"

	"vitess.io/vitess/go/timer"
	"vitess.io/vitess/go/vt/concurrency"
	"vitess.io/vitess/go/vt/dbconfigs"
	"vitess.io/vitess/go/vt/dtids"
	"vitess.io/vitess/go/vt/log"
	"vitess.io/vitess/go/vt/vtgate/vtgateconn"
	"vitess.io/vitess/go/vt/vttablet/tabletserver/connpool"
	"vitess.io/vitess/go/vt/vttablet/tabletserver/tabletenv"
	"vitess.io/vitess/go/vt/vttablet/tabletserver/txlimiter"

	querypb "vitess.io/vitess/go/vt/proto/query"
)

type txEngineState int

// The TxEngine can be in any of these states
const (
	NotServing txEngineState = iota
	Transitioning
	AcceptingReadAndWrite
	AcceptingReadOnly
)

func (state txEngineState) String() string {
	names := [...]string{
		"NotServing",
		"Transitioning",
		"AcceptReadWrite",
		"AcceptingReadOnly"}

	if state < NotServing || state > AcceptingReadOnly {
		return fmt.Sprintf("Unknown - %d", int(state))
	}

	return names[state]
}

// TxEngine is responsible for handling the tx-pool and keeping read-write, read-only or not-serving
// states. It will start and shut down the underlying tx-pool as required.
// It does this in a concurrently safe way.
type TxEngine struct {
	// the following four fields are interconnected. `state` and `nextState` should be protected by the
	// `stateLock`
	//
	// `nextState` is used when state is Transitioning. This means that in order to change the state of
	// the transaction engine, we had to close transactions. `nextState` is the state we'll end up in
	// once the transactions are closed
	// while transitioning, `transitionSignal` will contain an open channel. Once the transition is
	// over, the channel is closed to signal to any waiting goroutines that the state change is done.
	stateLock        sync.Mutex
	state            txEngineState
	nextState        txEngineState
	transitionSignal chan struct{}

	// beginRequests is used to make sure that we do not make a state
	// transition while creating new transactions
	beginRequests sync.WaitGroup

	dbconfigs *dbconfigs.DBConfigs

	twopcEnabled        bool
	shutdownGracePeriod time.Duration
	coordinatorAddress  string
	abandonAge          time.Duration
	ticks               *timer.Timer

	txPool       *TxPool
	preparedPool *TxPreparedPool
	twoPC        *TwoPC
}

// NewTxEngine creates a new TxEngine.
func NewTxEngine(checker connpool.MySQLChecker, config tabletenv.TabletConfig) *TxEngine {
	te := &TxEngine{
		shutdownGracePeriod: time.Duration(config.TxShutDownGracePeriod * 1e9),
	}
	limiter := txlimiter.New(
		config.TransactionCap,
		config.TransactionLimitPerUser,
		config.EnableTransactionLimit,
		config.EnableTransactionLimitDryRun,
		config.TransactionLimitByUsername,
		config.TransactionLimitByPrincipal,
		config.TransactionLimitByComponent,
		config.TransactionLimitBySubcomponent,
	)
	te.txPool = NewTxPool(
		config.PoolNamePrefix,
		config.TransactionCap,
		config.FoundRowsPoolSize,
		time.Duration(config.TransactionTimeout*1e9),
		time.Duration(config.IdleTimeout*1e9),
		config.TxPoolWaiterCap,
		checker,
		limiter,
	)
	te.twopcEnabled = config.TwoPCEnable
	if te.twopcEnabled {
		if config.TwoPCCoordinatorAddress == "" {
			log.Error("Coordinator address not specified: Disabling 2PC")
			te.twopcEnabled = false
		}
		if config.TwoPCAbandonAge <= 0 {
			log.Error("2PC abandon age not specified: Disabling 2PC")
			te.twopcEnabled = false
		}
	}
	te.coordinatorAddress = config.TwoPCCoordinatorAddress
	te.abandonAge = time.Duration(config.TwoPCAbandonAge * 1e9)
	te.ticks = timer.NewTimer(te.abandonAge / 2)

	// Set the prepared pool capacity to something lower than
	// tx pool capacity. Those spare connections are needed to
	// perform metadata state change operations. Without this,
	// the system can deadlock if all connections get moved to
	// the TxPreparedPool.
	te.preparedPool = NewTxPreparedPool(config.TransactionCap - 2)
	readPool := connpool.New(
		config.PoolNamePrefix+"TxReadPool",
		3,
		time.Duration(config.IdleTimeout*1e9),
		checker,
	)
	te.twoPC = NewTwoPC(readPool)
	te.transitionSignal = make(chan struct{})
	// By immediately closing this channel, all state changes can simply be made blocking by issuing the
	// state change desired, and then selecting on this channel. It will contain an open channel while
	// transitioning.
	close(te.transitionSignal)
	te.nextState = -1
	te.state = NotServing
	return te
}

// Stop will stop accepting any new transactions. Transactions are immediately aborted.
func (te *TxEngine) Stop() error {
	te.beginRequests.Wait()
	te.stateLock.Lock()

	switch te.state {
	case NotServing:
		// Nothing to do. We are already stopped or stopping
		te.stateLock.Unlock()
		return nil

	case AcceptingReadAndWrite:
		return te.transitionTo(NotServing)

	case AcceptingReadOnly:
		// We are not master, so it's safe to kill all read-only transactions
		te.close(true)
		te.state = NotServing
		te.stateLock.Unlock()
		return nil

	case Transitioning:
		te.nextState = NotServing
		te.stateLock.Unlock()
		te.blockUntilEndOfTransition()
		return nil

	default:
		te.stateLock.Unlock()
		return te.unknownStateError()
	}
}

// AcceptReadWrite will start accepting all transactions.
// If transitioning from RO mode, transactions might need to be
// rolled back before new transactions can be accepts.
func (te *TxEngine) AcceptReadWrite() error {
	te.beginRequests.Wait()
	te.stateLock.Lock()

	switch te.state {
	case AcceptingReadAndWrite:
		// Nothing to do
		te.stateLock.Unlock()
		return nil

	case NotServing:
		te.state = AcceptingReadAndWrite
		te.open()
		te.stateLock.Unlock()
		return nil

	case Transitioning:
		te.nextState = AcceptingReadAndWrite
		te.stateLock.Unlock()
		te.blockUntilEndOfTransition()
		return nil

	case AcceptingReadOnly:
		// We need to restart the tx-pool to make sure we handle 2PC correctly
		te.close(true)
		te.state = AcceptingReadAndWrite
		te.open()
		te.stateLock.Unlock()
		return nil

	default:
		return te.unknownStateError()
	}
}

// AcceptReadOnly will start accepting read-only transactions, but not full read and write transactions.
// If the engine is currently accepting full read and write transactions, they need to
// be rolled back.
func (te *TxEngine) AcceptReadOnly() error {
	te.beginRequests.Wait()
	te.stateLock.Lock()
	switch te.state {
	case AcceptingReadOnly:
		// Nothing to do
		te.stateLock.Unlock()
		return nil

	case NotServing:
		te.state = AcceptingReadOnly
		te.open()
		te.stateLock.Unlock()
		return nil

	case AcceptingReadAndWrite:
		return te.transitionTo(AcceptingReadOnly)

	case Transitioning:
		te.nextState = AcceptingReadOnly
		te.stateLock.Unlock()
		te.blockUntilEndOfTransition()
		return nil

	default:
		te.stateLock.Unlock()
		return te.unknownStateError()
	}
}

// Begin begins a transaction, and returns the associated transaction id.
// Subsequent statements can access the connection through the transaction id.
func (te *TxEngine) Begin(ctx context.Context, options *querypb.ExecuteOptions) (int64, error) {
	te.stateLock.Lock()

	canOpenTransactions := te.state == AcceptingReadOnly || te.state == AcceptingReadAndWrite
	if !canOpenTransactions {
		// We are not in a state where we can start new transactions. Abort.
		te.stateLock.Unlock()
		return 0, vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "tx engine can't accept new transactions in state %v", te.state)
	}

	isWriteTransaction := options == nil || options.TransactionIsolation != querypb.ExecuteOptions_CONSISTENT_SNAPSHOT_READ_ONLY
	if te.state == AcceptingReadOnly && isWriteTransaction {
		te.stateLock.Unlock()
		return 0, vterrors.Errorf(vtrpc.Code_UNAVAILABLE, "tx engine can only accept read-only transactions in current state")
	}

	// By Add() to beginRequests, we block others from initiating state
	// changes until we have finished adding this transaction
	te.beginRequests.Add(1)
	te.stateLock.Unlock()

	defer te.beginRequests.Done()
	return te.txPool.Begin(ctx, options)
}

// Commit commits the specified transaction.
func (te *TxEngine) Commit(ctx context.Context, transactionID int64, mc messageCommitter) error {
	return te.txPool.Commit(ctx, transactionID, mc)
}

// Rollback rolls back the specified transaction.
func (te *TxEngine) Rollback(ctx context.Context, transactionID int64) error {
	return te.txPool.Rollback(ctx, transactionID)
}

func (te *TxEngine) unknownStateError() error {
	return vterrors.Errorf(vtrpc.Code_INTERNAL, "unknown state %v", te.state)
}

func (te *TxEngine) blockUntilEndOfTransition() error {
	<-te.transitionSignal
	return nil
}

func (te *TxEngine) transitionTo(nextState txEngineState) error {
	te.state = Transitioning
	te.nextState = nextState
	te.transitionSignal = make(chan struct{})
	te.stateLock.Unlock()

	// We do this outside the lock so others can see our state while we close up waiting transactions
	te.close(true)

	te.stateLock.Lock()
	defer func() {
		// we use a lambda to make it clear in which order things need to happen
		te.stateLock.Unlock()
		close(te.transitionSignal)
	}()

	if te.state != Transitioning {
		return vterrors.Errorf(vtrpc.Code_INTERNAL, "this should never happen. the goroutine starting the transition should also finish it")
	}

	// Once we reach this point, it's as if our state is NotServing,
	// and we need to decide what the next step is
	switch te.nextState {
	case AcceptingReadAndWrite, AcceptingReadOnly:
		te.state = te.nextState
		te.open()
	case NotServing:
		te.state = NotServing
	case Transitioning:
		return vterrors.Errorf(vtrpc.Code_INTERNAL, "this should never happen. nextState cannot be transitioning")
	}

	te.nextState = -1

	return nil
}

// InitDBConfig must be called before Init.
func (te *TxEngine) InitDBConfig(dbcfgs *dbconfigs.DBConfigs) {
	te.dbconfigs = dbcfgs
}

// Init must be called once when vttablet starts for setting
// up the metadata tables.
func (te *TxEngine) Init() error {
	if te.twopcEnabled {
		return te.twoPC.Init(te.dbconfigs.SidecarDBName.Get(), te.dbconfigs.DbaWithDB())
	}
	return nil
}

// open opens the TxEngine. If 2pc is enabled, it restores
// all previously prepared transactions from the redo log.
// this should only be called when the state is already locked
func (te *TxEngine) open() {
	te.txPool.Open(te.dbconfigs.AppWithDB(), te.dbconfigs.DbaWithDB(), te.dbconfigs.AppDebugWithDB())

	if te.twopcEnabled && te.state == AcceptingReadAndWrite {
		te.twoPC.Open(te.dbconfigs)
		if err := te.prepareFromRedo(); err != nil {
			// If this operation fails, we choose to raise an alert and
			// continue anyway. Serving traffic is considered more important
			// than blocking everything for the sake of a few transactions.
			tabletenv.InternalErrors.Add("TwopcResurrection", 1)
			log.Errorf("Could not prepare transactions: %v", err)
		}
		te.startWatchdog()
	}
}

// StopGently will disregard common rules for when to kill transactions
// and wait forever for transactions to wrap up
func (te *TxEngine) StopGently() {
	te.stateLock.Lock()
	defer te.stateLock.Unlock()
	te.close(false)
	te.state = NotServing
}

// Close closes the TxEngine. If the immediate flag is on,
// then all current transactions are immediately rolled back.
// Otherwise, the function waits for all current transactions
// to conclude. If a shutdown grace period was specified,
// the transactions are rolled back if they're not resolved
// by that time.
func (te *TxEngine) close(immediate bool) {
	// Shut down functions are idempotent.
	// No need to check if 2pc is enabled.
	te.stopWatchdog()

	poolEmpty := make(chan bool)
	rollbackDone := make(chan bool)
	// This goroutine decides if transactions have to be
	// forced to rollback, and if so, when. Once done,
	// the function closes rollbackDone, which can be
	// verified to make sure it won't kick in later.
	go func() {
		defer func() {
			tabletenv.LogError()
			close(rollbackDone)
		}()
		if immediate {
			// Immediately rollback everything and return.
			log.Info("Immediate shutdown: rolling back now.")
			te.rollbackTransactions()
			return
		}
		if te.shutdownGracePeriod <= 0 {
			// No grace period was specified. Never rollback.
			te.rollbackPrepared()
			log.Info("No grace period specified: performing normal wait.")
			return
		}
		tmr := time.NewTimer(te.shutdownGracePeriod)
		defer tmr.Stop()
		select {
		case <-tmr.C:
			log.Info("Grace period exceeded: rolling back now.")
			te.rollbackTransactions()
		case <-poolEmpty:
			// The pool cleared before the timer kicked in. Just return.
			log.Info("Transactions completed before grace period: shutting down.")
		}
	}()
	te.txPool.WaitForEmpty()
	// If the goroutine is still running, signal that it can exit.
	close(poolEmpty)
	// Make sure the goroutine has returned.
	<-rollbackDone

	te.txPool.Close()
	te.twoPC.Close()
}

// prepareFromRedo replays and prepares the transactions
// from the redo log, loads previously failed transactions
// into the reserved list, and adjusts the txPool LastID
// to ensure there are no future collisions.
func (te *TxEngine) prepareFromRedo() error {
	ctx := tabletenv.LocalContext()
	var allErr concurrency.AllErrorRecorder
	prepared, failed, err := te.twoPC.ReadAllRedo(ctx)
	if err != nil {
		return err
	}

	maxid := int64(0)
outer:
	for _, tx := range prepared {
		txid, err := dtids.TransactionID(tx.Dtid)
		if err != nil {
			log.Errorf("Error extracting transaction ID from ditd: %v", err)
		}
		if txid > maxid {
			maxid = txid
		}
		conn, err := te.txPool.LocalBegin(ctx, &querypb.ExecuteOptions{})
		if err != nil {
			allErr.RecordError(err)
			continue
		}
		for _, stmt := range tx.Queries {
			conn.RecordQuery(stmt)
			_, err := conn.Exec(ctx, stmt, 1, false)
			if err != nil {
				allErr.RecordError(err)
				te.txPool.LocalConclude(ctx, conn)
				continue outer
			}
		}
		// We should not use the external Prepare because
		// we don't want to write again to the redo log.
		err = te.preparedPool.Put(conn, tx.Dtid)
		if err != nil {
			allErr.RecordError(err)
			continue
		}
	}
	for _, tx := range failed {
		txid, err := dtids.TransactionID(tx.Dtid)
		if err != nil {
			log.Errorf("Error extracting transaction ID from ditd: %v", err)
		}
		if txid > maxid {
			maxid = txid
		}
		te.preparedPool.SetFailed(tx.Dtid)
	}
	te.txPool.AdjustLastID(maxid)
	log.Infof("Prepared %d transactions, and registered %d failures.", len(prepared), len(failed))
	return allErr.Error()
}

// rollbackTransactions rolls back all open transactions
// including the prepared ones.
// This is used for transitioning from a master to a non-master
// serving type.
func (te *TxEngine) rollbackTransactions() {
	ctx := tabletenv.LocalContext()
	for _, c := range te.preparedPool.FetchAll() {
		te.txPool.LocalConclude(ctx, c)
	}
	// The order of rollbacks is currently not material because
	// we don't allow new statements or commits during
	// this function. In case of any such change, this will
	// have to be revisited.
	te.txPool.RollbackNonBusy(ctx)
}

func (te *TxEngine) rollbackPrepared() {
	ctx := tabletenv.LocalContext()
	for _, c := range te.preparedPool.FetchAll() {
		te.txPool.LocalConclude(ctx, c)
	}
}

// startWatchdog starts the watchdog goroutine, which looks for abandoned
// transactions and calls the notifier on them.
func (te *TxEngine) startWatchdog() {
	te.ticks.Start(func() {
		ctx, cancel := context.WithTimeout(tabletenv.LocalContext(), te.abandonAge/4)
		defer cancel()

		// Raise alerts on prepares that have been unresolved for too long.
		// Use 5x abandonAge to give opportunity for watchdog to resolve these.
		count, err := te.twoPC.CountUnresolvedRedo(ctx, time.Now().Add(-te.abandonAge*5))
		if err != nil {
			tabletenv.InternalErrors.Add("WatchdogFail", 1)
			log.Errorf("Error reading unresolved prepares: '%v': %v", te.coordinatorAddress, err)
		}
		tabletenv.Unresolved.Set("Prepares", count)

		// Resolve lingering distributed transactions.
		txs, err := te.twoPC.ReadAbandoned(ctx, time.Now().Add(-te.abandonAge))
		if err != nil {
			tabletenv.InternalErrors.Add("WatchdogFail", 1)
			log.Errorf("Error reading transactions for 2pc watchdog: %v", err)
			return
		}
		if len(txs) == 0 {
			return
		}

		coordConn, err := vtgateconn.Dial(ctx, te.coordinatorAddress)
		if err != nil {
			tabletenv.InternalErrors.Add("WatchdogFail", 1)
			log.Errorf("Error connecting to coordinator '%v': %v", te.coordinatorAddress, err)
			return
		}
		defer coordConn.Close()

		var wg sync.WaitGroup
		for tx := range txs {
			wg.Add(1)
			go func(dtid string) {
				defer wg.Done()
				if err := coordConn.ResolveTransaction(ctx, dtid); err != nil {
					tabletenv.InternalErrors.Add("WatchdogFail", 1)
					log.Errorf("Error notifying for dtid %s: %v", dtid, err)
				}
			}(tx)
		}
		wg.Wait()
	})
}

// stopWatchdog stops the watchdog goroutine.
func (te *TxEngine) stopWatchdog() {
	te.ticks.Stop()
}


text:
namespace Microsoft.Azure.Management.Synapse
{
    using Microsoft.Rest;
    using Microsoft.Rest.Azure;
    using Models;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Extension methods for WorkspaceManagedSqlServerEncryptionProtectorOperations.
    /// </summary>
    public static partial class WorkspaceManagedSqlServerEncryptionProtectorOperationsExtensions
    {
            /// <summary>
            /// Get workspace server's encryption protector.
            /// </summary>
            /// <remarks>
            /// Get workspace managed sql server's encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            public static EncryptionProtector Get(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName)
            {
                return operations.GetAsync(resourceGroupName, workspaceName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Get workspace server's encryption protector.
            /// </summary>
            /// <remarks>
            /// Get workspace managed sql server's encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<EncryptionProtector> GetAsync(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.GetWithHttpMessagesAsync(resourceGroupName, workspaceName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Updates workspace server's encryption protector.
            /// </summary>
            /// <remarks>
            /// Updates workspace managed sql server's encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='parameters'>
            /// The requested encryption protector resource state.
            /// </param>
            public static EncryptionProtector CreateOrUpdate(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName, EncryptionProtector parameters)
            {
                return operations.CreateOrUpdateAsync(resourceGroupName, workspaceName, parameters).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Updates workspace server's encryption protector.
            /// </summary>
            /// <remarks>
            /// Updates workspace managed sql server's encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='parameters'>
            /// The requested encryption protector resource state.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<EncryptionProtector> CreateOrUpdateAsync(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName, EncryptionProtector parameters, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.CreateOrUpdateWithHttpMessagesAsync(resourceGroupName, workspaceName, parameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Get list of encryption protectors for the server.
            /// </summary>
            /// <remarks>
            /// Get list of encryption protectors for workspace managed sql server.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            public static IPage<EncryptionProtector> List(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName)
            {
                return operations.ListAsync(resourceGroupName, workspaceName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Get list of encryption protectors for the server.
            /// </summary>
            /// <remarks>
            /// Get list of encryption protectors for workspace managed sql server.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<EncryptionProtector>> ListAsync(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListWithHttpMessagesAsync(resourceGroupName, workspaceName, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Revalidates server's existing encryption protector.
            /// </summary>
            /// <remarks>
            /// Revalidates workspace managed sql server's existing encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            public static void Revalidate(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName)
            {
                operations.RevalidateAsync(resourceGroupName, workspaceName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Revalidates server's existing encryption protector.
            /// </summary>
            /// <remarks>
            /// Revalidates workspace managed sql server's existing encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task RevalidateAsync(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.RevalidateWithHttpMessagesAsync(resourceGroupName, workspaceName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Updates workspace server's encryption protector.
            /// </summary>
            /// <remarks>
            /// Updates workspace managed sql server's encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='parameters'>
            /// The requested encryption protector resource state.
            /// </param>
            public static EncryptionProtector BeginCreateOrUpdate(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName, EncryptionProtector parameters)
            {
                return operations.BeginCreateOrUpdateAsync(resourceGroupName, workspaceName, parameters).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Updates workspace server's encryption protector.
            /// </summary>
            /// <remarks>
            /// Updates workspace managed sql server's encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='parameters'>
            /// The requested encryption protector resource state.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<EncryptionProtector> BeginCreateOrUpdateAsync(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName, EncryptionProtector parameters, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.BeginCreateOrUpdateWithHttpMessagesAsync(resourceGroupName, workspaceName, parameters, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

            /// <summary>
            /// Revalidates server's existing encryption protector.
            /// </summary>
            /// <remarks>
            /// Revalidates workspace managed sql server's existing encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            public static void BeginRevalidate(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName)
            {
                operations.BeginRevalidateAsync(resourceGroupName, workspaceName).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Revalidates server's existing encryption protector.
            /// </summary>
            /// <remarks>
            /// Revalidates workspace managed sql server's existing encryption protector.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='resourceGroupName'>
            /// The name of the resource group. The name is case insensitive.
            /// </param>
            /// <param name='workspaceName'>
            /// The name of the workspace.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task BeginRevalidateAsync(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string resourceGroupName, string workspaceName, CancellationToken cancellationToken = default(CancellationToken))
            {
                (await operations.BeginRevalidateWithHttpMessagesAsync(resourceGroupName, workspaceName, null, cancellationToken).ConfigureAwait(false)).Dispose();
            }

            /// <summary>
            /// Get list of encryption protectors for the server.
            /// </summary>
            /// <remarks>
            /// Get list of encryption protectors for workspace managed sql server.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            public static IPage<EncryptionProtector> ListNext(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string nextPageLink)
            {
                return operations.ListNextAsync(nextPageLink).GetAwaiter().GetResult();
            }

            /// <summary>
            /// Get list of encryption protectors for the server.
            /// </summary>
            /// <remarks>
            /// Get list of encryption protectors for workspace managed sql server.
            /// </remarks>
            /// <param name='operations'>
            /// The operations group for this extension method.
            /// </param>
            /// <param name='nextPageLink'>
            /// The NextLink from the previous successful call to List operation.
            /// </param>
            /// <param name='cancellationToken'>
            /// The cancellation token.
            /// </param>
            public static async Task<IPage<EncryptionProtector>> ListNextAsync(this IWorkspaceManagedSqlServerEncryptionProtectorOperations operations, string nextPageLink, CancellationToken cancellationToken = default(CancellationToken))
            {
                using (var _result = await operations.ListNextWithHttpMessagesAsync(nextPageLink, null, cancellationToken).ConfigureAwait(false))
                {
                    return _result.Body;
                }
            }

    }
}


text:
SYNONYM

#### According to
Integrated Taxonomic Information System

#### Published in
V. L. Komarov, Fl. URSS 26:373. 1961

#### Original name
null

### Remarks
null


text:
using System.Drawing;
using OpenLiveWriter.ApplicationFramework.Preferences;
using OpenLiveWriter.CoreServices.Settings;

namespace OpenLiveWriter.PostEditor.PostHtmlEditing
{
    public sealed class ImageEditingSettings
    {

        public static Size DefaultImageSizeLarge
        {
            get { return SettingsKey.GetSize(LARGE_IMAGE_SIZE, new Size(1024, 768)); }
            set { SettingsKey.SetSize(LARGE_IMAGE_SIZE, value); }
        }
        private const string LARGE_IMAGE_SIZE = "ImageSizeLarge";

        public static Size DefaultImageSizeMedium
        {
            get { return SettingsKey.GetSize(MEDIUM_IMAGE_SIZE, new Size(640, 480)); }
            set { SettingsKey.SetSize(MEDIUM_IMAGE_SIZE, value); }
        }
        private const string MEDIUM_IMAGE_SIZE = "ImageSizeMedium";

        public static Size DefaultImageSizeSmall
        {
            get { return SettingsKey.GetSize(SMALL_IMAGE_SIZE, new Size(240, 240)); }
            set { SettingsKey.SetSize(SMALL_IMAGE_SIZE, value); }
        }
        private const string SMALL_IMAGE_SIZE = "ImageSizeSmall";

        internal static SettingsPersisterHelper SettingsKey = HtmlEditorSettings.SettingsKey.GetSubSettings("ImageEditing");
    }
    public enum ImageBorderType { None, DropShadow, Photo };
}


text:
{{/*
  Use Hugo's native Table of contents feature. You must set `toc: true` in your parameters for this to show.
  https://gohugo.io/content-management/toc/
*/}}

{{- if .Params.toc -}}

What's in this {{ humanize .Type }}

      {{ .TableOfContents }}

{{- end -}}

{{/*
  Use Hugo's native related content feature to pull in content that may have similar parameters, like tags. etc.
  https://gohugo.io/content-management/related/
*/}}

{{ $related := .Site.RegularPages.Related . | first 15 }}

{{ with $related }}

Related

	   {{ range . }}

            {{- .Title -}}

	    {{ end }}

{{ end }}


text:
package com.t2t.top.constant;

public class Option {
    private int code;
    private String value;

    public Option(int code, String value) {
        this.code = code;
        this.value = value;
    }

    public String getValue() {
        return value;
    }
    public int getCode() {
        return code;
    }
}


text:
#include "listener.hh"

namespace moulette
{
  void
  Listener::testStarting(const Testable * /*test*/)
  {
  }

  void
  Listener::testFinished(const Testable * /*test*/)
  {
  }

  void
  Listener::finished()
  {
  }
}


text:
(function($) {
    $(document).ready(function(){
        showHideButton();
        $('.cms-tabset-nav-primary li').on('click', showHideButton);

        function showHideButton() {
            if ($('#Root_Mailblock_set').is(':visible')) {
                $('#Form_EditForm_action_mailblockTestEmail').show();
            }
            else {
                $('#Form_EditForm_action_mailblockTestEmail').hide();
            }
        }
    })
})(jQuery);


text:
package com.android.mms.transaction;

import android.os.Bundle;

import com.android.internal.telephony.uicc.IccUtils;

/**
 * A wrapper around the Bundle instances used to start the TransactionService.
 * It provides high-level APIs to set the information required for the latter to
 * instantiate transactions.
 */
public class TransactionBundle {
    /**
     * Key for the transaction-type.
     * Allowed values for this key are: TYPE_PUSH_TRANSACTION, TYPE_RETRIEVE_TRANSACTION,
     * TYPE_SEND_TRANSACTION, and TYPE_READREC_TRANSACTION.
     */
    public static final String TRANSACTION_TYPE = "type";

    /**
     * Key of the push-data.
     * Used when TRANSACTION_TYPE is TYPE_PUSH_TRANSACTION.
     */
    private static final String PUSH_DATA = "mms-push-data";

    /**
     * Key of the MMSC server URL.
     */
    private static final String MMSC_URL = "mmsc-url";

    /**
     * Key of the HTTP Proxy address.
     */
    private static final String PROXY_ADDRESS = "proxy-address";

    /**
     * Key of the HTTP Proxy port.
     */
    private static final String PROXY_PORT = "proxy-port";

    /**
     * Key of the URI.
     * Indicates the URL of the M-Retrieve.conf in TYPE_RETRIEVE_TRANSACTION, or the
     * Uri of the M-Send.req/M-Read-Rec.ind in TYPE_SEND_TRANSACTION and
     * TYPE_READREC_TRANSACTION, respectively.
     */
    public static final String URI = "uri";

    /**
     * This is the real Bundle to be sent to the TransactionService upon calling
     * startService.
     */
    private final Bundle mBundle;

    /**
     * Private constructor.
     *
     * @param transactionType
     */
    private TransactionBundle(int transactionType) {
        mBundle = new Bundle();
        mBundle.putInt(TRANSACTION_TYPE, transactionType);
    }

    /**
     * Constructor of a bundle used for TransactionBundle instances of type
     * TYPE_RETRIEVE_TRANSACTION, TYPE_SEND_TRANSACTION, and TYPE_READREC_TRANSACTION.
     *
     * @param transactionType
     * @param uri The relevant URI for this transaction. Indicates the URL of the
     * M-Retrieve.conf in TYPE_RETRIEVE_TRANSACTION, or the Uri of the
     * M-Send.req/M-Read-Rec.ind in TYPE_SEND_TRANSACTION and
     * TYPE_READREC_TRANSACTION, respectively.
     */
    public TransactionBundle(int transactionType, String uri) {
        this(transactionType);
        mBundle.putString(URI, uri);
    }

    /**
     * Constructor of a transaction bundle used for incoming bundle instances.
     *
     * @param bundle The incoming bundle
     */
    public TransactionBundle(Bundle bundle) {
        mBundle = bundle;
    }

    public void setConnectionSettings(String mmscUrl,
            String proxyAddress,
            int proxyPort) {
        mBundle.putString(MMSC_URL, mmscUrl);
        mBundle.putString(PROXY_ADDRESS, proxyAddress);
        mBundle.putInt(PROXY_PORT, proxyPort);
    }

    public void setConnectionSettings(TransactionSettings settings) {
        setConnectionSettings(
                settings.getMmscUrl(),
                settings.getProxyAddress(),
                settings.getProxyPort());
    }

    public Bundle getBundle() {
        return mBundle;
    }

    public int getTransactionType() {
        return mBundle.getInt(TRANSACTION_TYPE);
    }

    public String getUri() {
        return mBundle.getString(URI);
    }

    public byte[] getPushData() {
        return mBundle.getByteArray(PUSH_DATA);
    }

    public String getMmscUrl() {
        return mBundle.getString(MMSC_URL);
    }

    public String getProxyAddress() {
        return mBundle.getString(PROXY_ADDRESS);
    }

    public int getProxyPort() {
        return mBundle.getInt(PROXY_PORT);
    }

    @Override
    public String toString() {
        return "transactionType: " + getTransactionType() +
            " uri: " + getUri() +
            " pushData: " + IccUtils.bytesToHexString(getPushData()) +
            " mmscUrl: " + getMmscUrl() +
            " proxyAddress: " + getProxyAddress() +
            " proxyPort: " + getProxyPort();
    }
}


text:
This page covers configuration of the mission computer for a demo
flight. First, make sure you have uploaded
the [flight computer software][standalone].

[standalone]: standalone.html

You will then have to make sure that uboot is installed, that the
seL4-based mission computer is installed, and that the filesystem for
the untrusted Linux VM demo component is flashed to the eMMC storage.

## Flash uboot

Follow the instructions [here](https://docs.sel4.systems/Hardware/jetsontk1?highlight=%28uboot%29#Flash_U-Boot)

## Load mission computer image

Follow the instructions [here](https://docs.sel4.systems/Hardware/CEI_TK1_SOM).

A few notes about the uploading: for debugging, it is possible to set
up FTP on the GCS and DHCP file transfer on the TK1/uboot.  This is a
bit of a pain to set up on the host side (hence we don't provide
specific instructions), but works fine once going.

For the actual flight we use USB loading. That means we put a USB
stick into the TK1's *blue* usb port. The USB stick has a file
called `sel4.img` which contains the TK1 image. Then we have uboot
configured to do a USB boot.

The uboot sequence is:

```
usb start
load usb 0:1 0x81000000 sel4.img
bootelf 0x81000000
```

**NOTE:** if your image has a different name than `sel4.img`, make
sure to modify the command accordingly.

If that works, you can save it as the default boot command with

```
setenv bootcmd "usb start; load usb 0:1 0x81000000 sel4.img; bootelf 0x81000000"
saveenv
```

To boot the actual vehicle:

1. Plug in the USB stick
2. Press the daughterboard reset button
3. Count to 10 seconds
4. Remove the USB stick, and wait for the rest of the system to boot

## Load the Linux filesystem

Download the Linux filesystem image from Dropbox [here](https://www.dropbox.com/s/w0mao28ekccld4m/backup-tk1.tar.gz?dl=0) and unzip it.

Go into uboot and do:

```
ums mmc 0
```

This makes the eMMC storage available as a USB mass storage
device. Then connect the mini-USB port on the TK1 to your
computer. You should see a new drive, such as `/dev/sdb1`, which you
can mount and read/write. You can wipe out what's there already and
replace it with the proper downloaded. Make sure to use the `-r` flag
to `cp` to preserve permissions. Run `sync` afterwatds to make sure
all files got properly copied.

The files relevant for the [demo flight][demo] are under `/root` directory.

## Upload Pixy cam software

Follow the instructions [here](../hardware/iris.html#pixycam).

## Ready to fly?

Proceed to [preflight preparations][preflight] or check out the example of [demo flight][demo].

[preflight]: preflight.html
[demo]: demo_script.html


text:
package pl.olszak.michal.detector.system.configuration;

import org.opencv.core.Core;
import org.springframework.context.annotation.Configuration;

/**
 * @author molszak
 *         created on 22.03.2017.
 */
@Configuration
public class OpenCvConfiguration {

    static {
        nu.pattern.OpenCV.loadShared();
        System.loadLibrary(Core.NATIVE_LIBRARY_NAME);
    }

}


text:
package main

import (
	"flag"
	"fmt"
	"os"
	"os/signal"
	"syscall"

	"github.com/Symantec/Dominator/lib/constants"
	"github.com/Symantec/Dominator/lib/fsutil"
	"github.com/Symantec/Dominator/lib/log"
	"github.com/Symantec/Dominator/lib/log/serverlogger"
	"github.com/Symantec/Dominator/lib/mdb"
	"github.com/Symantec/tricorder/go/tricorder"
)

var (
	datacentre = flag.String("datacentre", "",
		"Datacentre to limit results to (may not be supported by all drivers)")
	debug         = flag.Bool("debug", false, "If true, show debugging output")
	fetchInterval = flag.Uint("fetchInterval", 59,
		"Interval between fetches from the MDB source, in seconds")
	hostnameRegex = flag.String("hostnameRegex", ".*",
		"A regular expression to match the desired hostnames")
	mdbFile = flag.String("mdbFile", "/var/lib/Dominator/mdb",
		"Name of file to write filtered MDB data to")
	portNum = flag.Uint("portNum", constants.SimpleMdbServerPortNumber,
		"Port number to allocate and listen on for HTTP/RPC")
	sourcesFile = flag.String("sourcesFile",
		"/var/lib/Dominator/mdb.sources.list",
		"Name of file list of driver url pairs")
	pidfile = flag.String("pidfile", "", "Name of file to write my PID to")
)

func printUsage() {
	fmt.Fprintln(os.Stderr,
		"Usage: mdbd [flags...]")
	fmt.Fprintln(os.Stderr, "Common flags:")
	flag.PrintDefaults()
	fmt.Fprintln(os.Stderr, "Drivers:")
	fmt.Fprintln(os.Stderr,
		"  aws: region account")
	fmt.Fprintln(os.Stderr,
		"    Query Amazon AWS")
	fmt.Fprintln(os.Stderr,
		"    region: a datacentre like 'us-east-1'")
	fmt.Fprintln(os.Stderr,
		"    account: the profile to use out of ~/.aws/credentials which")
	fmt.Fprintln(os.Stderr,
		"             contains the amazon aws credentials. For additional")
	fmt.Fprintln(os.Stderr,
		"             information see:")
	fmt.Fprintln(os.Stderr,
		"             http://docs.aws.amazon.com/sdk-for-go/latest/v1/developerguide/sdkforgo-dg.pdf")
	fmt.Fprintln(os.Stderr,
		"  aws-filtered: targets filter-tags-file")
	fmt.Fprintln(os.Stderr,
		"    Query Amazon AWS")
	fmt.Fprintln(os.Stderr,
		"    targets: a list of targets, i.e. 'prod,us-east-1;dev,us-east-1'")
	fmt.Fprintln(os.Stderr,
		"    filter-tags-file: a JSON file of tags to filter for")
	fmt.Fprintln(os.Stderr,
		"  aws-local")
	fmt.Fprintln(os.Stderr,
		"    Query Amazon AWS for all acccounts for the local region")
	fmt.Fprintln(os.Stderr,
		"  cis: url")
	fmt.Fprintln(os.Stderr,
		"    url: Cloud Intelligence Service endpoint search query")
	fmt.Fprintln(os.Stderr,
		"  ds.host.fqdn: url")
	fmt.Fprintln(os.Stderr,
		"    url: URL which yields JSON with map of map of hosts with fqdn entries")
	fmt.Fprintln(os.Stderr,
		"  text: url")
	fmt.Fprintln(os.Stderr,
		"    url: URL which yields lines. Each line contains:")
	fmt.Fprintln(os.Stderr,
		"         host [required-image [planned-image]]")
}

type driver struct {
	name      string
	minArgs   int
	maxArgs   int
	setupFunc makeGeneratorFunc
}

var drivers = []driver{
	{"aws", 2, 2, newAwsGenerator},
	{"aws-filtered", 2, 2, newAwsFilteredGenerator},
	{"aws-local", 0, 0, newAwsLocalGenerator},
	{"cis", 1, 1, newCisGenerator},
	{"ds.host.fqdn", 1, 1, newDsHostFqdnGenerator},
	{"text", 1, 1, newTextGenerator},
}

func gracefulCleanup() {
	os.Remove(*pidfile)
	os.Exit(1)
}

func writePidfile() {
	file, err := os.Create(*pidfile)
	if err != nil {
		return
	}
	defer file.Close()
	fmt.Fprintln(file, os.Getpid())
}

func handleSignals(logger log.Logger) {
	if *pidfile == "" {
		return
	}
	sigtermChannel := make(chan os.Signal)
	signal.Notify(sigtermChannel, syscall.SIGTERM, syscall.SIGINT)
	writePidfile()
	go func() {
		for {
			select {
			case <-sigtermChannel:
				gracefulCleanup()
			}
		}
	}()
}

func showErrorAndDie(err error) {
	fmt.Fprintln(os.Stderr, err)
	os.Exit(2)
}

func main() {
	flag.Usage = printUsage
	flag.Parse()
	tricorder.RegisterFlags()
	logger := serverlogger.New("")
	// We have to have inputs.
	if *sourcesFile == "" {
		printUsage()
		os.Exit(2)
	}
	handleSignals(logger)
	readerChannel := fsutil.WatchFile(*sourcesFile, logger)
	file, err := os.Open(*sourcesFile)
	if err != nil {
		showErrorAndDie(err)
	}
	(<-readerChannel).Close()
	generators, err := setupGenerators(file, drivers)
	file.Close()
	if err != nil {
		showErrorAndDie(err)
	}
	httpSrv, err := startHttpServer(*portNum)
	if err != nil {
		showErrorAndDie(err)
	}
	httpSrv.AddHtmlWriter(logger)
	rpcd := startRpcd(logger)
	go runDaemon(generators, *mdbFile, *hostnameRegex, *datacentre,
		*fetchInterval, func(old, new *mdb.Mdb) {
			rpcd.pushUpdateToAll(old, new)
			httpSrv.UpdateMdb(new)
		},
		logger, *debug)
	<-readerChannel
	fsutil.WatchFileStop()
	if err := syscall.Exec(os.Args[0], os.Args, os.Environ()); err != nil {
		logger.Printf("Unable to Exec:%s: %s\n", os.Args[0], err)
	}
}


text:
class Environment(object):
    def __init__(self):
        self.token = None
        self.tenant_id = None