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

/**
 * @fileoverview Entry point for the SafariDriver extension's global script.
 */

goog.provide('safaridriver.extension');

goog.require('bot.response');
goog.require('goog.asserts');
goog.require('goog.debug.LogManager');
goog.require('goog.debug.Logger');
goog.require('safaridriver.console');
goog.require('safaridriver.extension.LogDb');
goog.require('safaridriver.extension.Server');
goog.require('safaridriver.extension.Session');
goog.require('safaridriver.extension.TabManager');
goog.require('safaridriver.logging.ForwardingHandler');
goog.require('safaridriver.message');
goog.require('safaridriver.message.Alert');
goog.require('safaridriver.message.Command');
goog.require('safaridriver.message.Connect');
goog.require('safaridriver.message.LoadModule');
goog.require('safaridriver.message.Response');
goog.require('webdriver.Session');
goog.require('webdriver.WebDriver');
goog.require('webdriver.logging');

/**
 * Initializes the SafariDriver extension's global page.
 */
safaridriver.extension.init = function() {
  goog.debug.LogManager.getRoot().setLevel(goog.debug.Logger.Level.ALL);
  safaridriver.console.init();

  // Wait for the logging database to initialize before continuing. This will
  // ensure we can capture all of the logging output. This should be no more
  // than a setTimeout(fn, 0) wait (depends on the current machine though).
  safaridriver.extension.LogDb.getInstance().isReady().
      then(safaridriver.extension.postLogInit_);
};

/** @private */
safaridriver.extension.postLogInit_ = function() {
  goog.debug.LogManager.getRoot().addHandler(function(logRecord) {
    var entry = webdriver.logging.Entry.fromClosureLogRecord(
        logRecord, webdriver.logging.Type.DRIVER);
    safaridriver.extension.LogDb.getInstance().save([entry]);
  });

  safaridriver.extension.LOG_.fine('Creating global session...');
  safaridriver.extension.tabManager_ = new safaridriver.extension.TabManager();
  safaridriver.extension.session_ = new safaridriver.extension.Session(
      safaridriver.extension.tabManager_);

  safaridriver.extension.LOG_.fine('Creating debug driver...');
  var server = safaridriver.extension.createSessionServer_();
  safaridriver.extension.driver = new webdriver.WebDriver(
      new webdriver.Session('debug', {}), server);
  goog.exportSymbol('driver', safaridriver.extension.driver);

  safari.application.addEventListener(
      'message', safaridriver.extension.onMessage_, false);
  safari.application.addEventListener(
      'command', safaridriver.extension.onCommand_, false);

  // Now that we're initialized, we sit and wait for a page to send us a client
  // to attempt connecting to.
  safaridriver.extension.LOG_.info('Waiting for connect command...');
};

/**
 * @private {!goog.debug.Logger}
 * @const
 */
safaridriver.extension.LOG_ = goog.debug.Logger.getLogger(
    'safaridriver.extension');

/**
 * Global tab manager shared by each instance; lazily initialized in
 * {@link safaridriver.extension.init}.
 * @private {!safaridriver.extension.TabManager}
 */
safaridriver.extension.tabManager_;

/**
 * Global session shared by eash clinet; lazily initialized in
 * {@link safaridriver.extension.init}.
 * @private {!safaridriver.extension.Session}
 */
safaridriver.extension.session_;

/**
 * An instance of {@link webdriver.WebDriver}, provided for interacting with
 * the extension via the global page's REPL.
 * @type {webdriver.WebDriver}
 */
safaridriver.extension.driver;

/**
 * The number of WebDriver client connections active with this extension.
 * @private {number}
 */
safaridriver.extension.numConnections_ = 0;

/**
 * @private {string}
 * @const
 */
safaridriver.extension.LOG_PAGE_URL_ = safari.extension.baseURI + 'log.html';

/**
 * The tab to display logging info in.
 * @private {SafariBrowserTab}
 */
safaridriver.extension.loggingTab_ = null;

/** @private {safaridriver.logging.ForwardingHandler} */
safaridriver.extension.logHandler_ = null;

/**
 * Opens the logging tab if it is not currently open.
 * @private
 */
safaridriver.extension.openLogWindow_ = function() {
  if (!safaridriver.extension.loggingTab_) {
    var win = safari.application.openBrowserWindow();
    safaridriver.extension.loggingTab_ = win.activeTab;
    safaridriver.extension.loggingTab_.addEventListener(
        'close', onClose, true);

    safaridriver.extension.logHandler_ =
        new safaridriver.logging.ForwardingHandler(
            safaridriver.extension.loggingTab_.page);

    safaridriver.extension.tabManager_.ignoreTab(
        safaridriver.extension.loggingTab_);
  }

  if (safaridriver.extension.loggingTab_.url !==
      safaridriver.extension.LOG_PAGE_URL_) {
    safaridriver.extension.loggingTab_.addEventListener(
        'navigate', onLoad, true);
    safaridriver.extension.loggingTab_.url =
        safaridriver.extension.LOG_PAGE_URL_;
  }

  function onClose() {
    safaridriver.extension.loggingTab_.removeEventListener(
        'close', onClose, true);
    safaridriver.extension.loggingTab_ = null;

    safaridriver.extension.logHandler_.dispose();
    safaridriver.extension.logHandler_ = null;
  }

  function onLoad() {
    safaridriver.extension.loggingTab_.removeEventListener(
        'navigate', onLoad, true);

    if (safaridriver.extension.loggingTab_.url !==
        safaridriver.extension.LOG_PAGE_URL_) {
      return;  // Navigated to another page.
    }

    safaridriver.extension.LogDb.getInstance().get().
        then(function(entries) {
          var message = new safaridriver.message.Log(entries);
          message.send(safaridriver.extension.loggingTab_.page);
        });
  }
};

/**
 * Responds to command events from the Safari application.
 * @param {!SafariCommandEvent} e The event.
 * @private
 */
safaridriver.extension.onCommand_ = function(e) {
  if (e.command === 'showlog') {
    safaridriver.extension.openLogWindow_();
  }
};

/**
 * Responds to a message from an injected script. Note this event listener is
 * attached to the {@code safari.application} object and will receive messages
 * after any listeners attached directly to a tab or browser.
 * @param {!SafariExtensionMessageEvent} e The event.
 * @private
 */
safaridriver.extension.onMessage_ = function(e) {
  var isSynchronous = e.name === 'canLoad';
  var message = safaridriver.message.fromEvent(e);
  var type = message.getType();
  switch (type) {
    case safaridriver.message.Command.TYPE:
      var command = /** @type {!safaridriver.message.Command} */ (message).
          getCommand();

      var server = safaridriver.extension.createSessionServer_();
      server.execute(command, function(error, responseObj) {
        // Only send responses to the logging window. If the window is no longer
        // open, there's nothing to send the response to.
        if (!safaridriver.extension.loggingTab_) {
          return;
        }

        if (error) {
          responseObj = bot.response.createErrorResponse(error);
        }

        var response = new safaridriver.message.Response(command.getId(),
            /** @type {bot.response.ResponseObject} */ (responseObj));
        response.send(safaridriver.extension.loggingTab_.page);
      });
      break;

    case safaridriver.message.Connect.TYPE:
      var url = /** @type {!safaridriver.message.Connect} */ (message).getUrl();

      // If the message was sent synchronously, acknowledge the request. The
      // message will be async if this extension is being used with an older
      // version of the SafariDriver client.
      if (isSynchronous) {
        e.message = true;
      }

      var server = safaridriver.extension.createSessionServer_();
      server.connect(url).
          then(function() {
            safaridriver.extension.LOG_.info('Connected to client: ' + url);
            safaridriver.extension.numConnections_++;
            server.onDispose(function() {
              safaridriver.extension.numConnections_--;
            });
          }, function(e) {
            safaridriver.extension.LOG_.severe(
                'Failed to connect to client: ' + url, e);
          });
      break;

    case safaridriver.message.Alert.TYPE:
      checkIsSynchronous();
      if (message.blocksUiThread() &&
          !safaridriver.extension.session_.isExecutingCommand()) {
        safaridriver.extension.LOG_.warning(
            'Saving unhandled alert text: ' + message.getMessage());
        safaridriver.extension.session_.setUnhandledAlertText(
            message.getMessage());
      }

      // TODO: Fully support alerts. See
      // http://code.google.com/p/selenium/issues/detail?id=3862
      e.message = !!safaridriver.extension.numConnections_;
      break;

    case safaridriver.message.Log.TYPE:
      if (safaridriver.extension.logHandler_) {
        safaridriver.extension.logHandler_.forward(
            /** @type {!safaridriver.message.Log} */ (message));
      }
      safaridriver.extension.LogDb.getInstance().save(
          /** @type {!safaridriver.message.Log} */ (message).getEntries());
      break;

    case safaridriver.message.LoadModule.TYPE:
      checkIsSynchronous();
      e.message = safaridriver.extension.loadModule_(message.getModuleId());
      break;
  }

  function checkIsSynchronous() {
    goog.asserts.assert(isSynchronous,
        'Expected a synchronous message for type %s', type);
  }
};

/**
 * Creates a new session. The SafariDriver supports multiple sessions, each
 * with their own timeouts, but they all share the same tab manager.
 * @return {!safaridriver.extension.Server} The new server.
 * @private
 */
safaridriver.extension.createSessionServer_ = function() {
  return new safaridriver.extension.Server(safaridriver.extension.session_);
};

/**
 * @param {string} moduleId The module to load.
 * @return {!bot.response.ResponseObject} The response.
 * @private
 */
safaridriver.extension.loadModule_ = function(moduleId) {
  safaridriver.extension.LOG_.config('Loading module(' + moduleId + ')');
  var moduleFn = safaridriver.extension.modules_[moduleId];
  if (moduleFn) {
    return bot.response.createResponse(moduleFn.toString());
  }
  safaridriver.extension.LOG_.warning('module not found: ' + moduleId);
  return bot.response.createErrorResponse(
      Error('Internal error: module ' + moduleId + ' not found'));
};

/**
 * Object hash for compiled modules for lazy loading from the injected script.
 * @private {!Object.<function()>}
 */
safaridriver.extension.modules_ = {};
goog.exportSymbol('MODULES', safaridriver.extension.modules_);


text:
from typing import Dict, List, Optional, Tuple, Union, cast

import logging
import warnings

import numpy as np
import pandas as pd
from pandas.api.types import is_numeric_dtype, is_sparse
from scipy.sparse import csr_matrix, spmatrix
from sklearn.base import BaseEstimator
from sklearn.exceptions import NotFittedError

from autosklearn.util.logging_ import PickableLoggerAdapter

SUPPORTED_FEAT_TYPES = Union[List, pd.DataFrame, np.ndarray, spmatrix]

class FeatureValidator(BaseEstimator):
    """
    Checks the input data to Auto-Sklearn.

    It also determines what columns are categorical and which ones are numerical,
    so that the pre-processing pipeline can process this columns accordingly.

    Attributes
    ----------
    feat_type: Optional[List[str]] = None
        In case the dataset is not a pandas DataFrame:
            +   If provided, this list indicates which columns should be treated as
                categorical it is internally transformed into a dictionary that
                indicates a mapping from column index to categorical/numerical.
            +   If not provided, by default all columns are treated as numerical

        If the input dataset is of type pandas dataframe, this argument
        must be none, as the column type will be inferred from the pandas dtypes.

    data_type:
        Class name of the data type provided during fit.
    """

    def __init__(
        self,
        feat_type: Optional[List[str]] = None,
        logger: Optional[PickableLoggerAdapter] = None,
        allow_string_features: bool = True,
    ) -> None:
        # If a dataframe was provided, we populate
        # this attribute with a mapping from column to
        # {numerical | categorical | string}
        self.feat_type: Optional[Dict[Union[str, int], str]] = None
        if feat_type is not None:
            if isinstance(feat_type, dict):
                self.feat_type = feat_type
            elif not isinstance(feat_type, List):
                raise ValueError(
                    "Auto-Sklearn expects a list of categorical/"
                    "numerical/string feature types, yet a"
                    " {} was provided".format(type(feat_type))
                )
            else:

                # Convert to a dictionary which will be passed to the ColumnTransformer
                # Column Transformer supports strings or integer indexes
                self.feat_type = {i: feat for i, feat in enumerate(feat_type)}

        # Register types to detect unsupported data format changes
        self.data_type = None  # type: Optional[type]
        self.dtypes = {}  # type: Dict[str, str]

        self.logger = logger if logger is not None else logging.getLogger(__name__)

        self._is_fitted = False
        self.allow_string_features = allow_string_features

    def fit(
        self,
        X_train: SUPPORTED_FEAT_TYPES,
        X_test: Optional[SUPPORTED_FEAT_TYPES] = None,
    ) -> "FeatureValidator":
        """
        Validates input data to Auto-Sklearn.
        The supported data types are List, numpy arrays and pandas DataFrames.
        CSR sparse data types are also supported

        Parameters
        ----------
        X_train: SUPPORTED_FEAT_TYPES
            A set of features that are going to be validated (type and dimensionality
            checks) and a encoder fitted in the case the data needs encoding
        X_test: Optional[SUPPORTED_FEAT_TYPES]
            A hold out set of data used for checking
        """
        # If a list was provided, it will be converted to pandas
        if isinstance(X_train, List):
            X_train, X_test = self.list_to_dataframe(X_train, X_test)

        self._check_data(X_train)

        # Handle categorical feature identification for the pipeline
        if hasattr(X_train, "iloc"):
            if self.feat_type is not None:
                raise ValueError(
                    "When providing a DataFrame to Auto-Sklearn, we extract "
                    "the feature types from the DataFrame.dtypes. That is, "
                    "providing the option feat_type to the fit method is not "
                    "supported when using a Dataframe. Please make sure that the "
                    "type of each column in your DataFrame is properly set. "
                    "More details about having the correct data type in your "
                    "DataFrame can be seen in "
                    "https://pandas.pydata.org/pandas-docs/stable/reference"
                    "/api/pandas.DataFrame.astype.html"
                )
            else:
                self.feat_type = self.get_feat_type_from_columns(X_train)
        else:
            # Numpy array was provided
            if self.feat_type is None:
                # Assume numerical columns if a numpy array has no feature types
                self.feat_type = {i: "numerical" for i in range(np.shape(X_train)[1])}
            else:
                # Check The feat type provided
                if len(self.feat_type) != np.shape(X_train)[1]:
                    raise ValueError(
                        "Array feat_type does not have same number of "
                        "variables as X has features. %d vs %d."
                        % (len(self.feat_type), np.shape(X_train)[1])
                    )
                if not all([isinstance(f, str) for f in self.feat_type.values()]):
                    raise ValueError(
                        "feat_type must only contain strings: {}".format(
                            list(self.feat_type.values()),
                        )
                    )

                for ft in self.feat_type.values():
                    if ft.lower() not in ["categorical", "numerical", "string"]:
                        raise ValueError(
                            "Only `Categorical`, `Numerical` and `String` are "
                            "valid feature types"
                        )

        if X_test is not None:
            self._check_data(X_test)

            if np.shape(X_train)[1] != np.shape(X_test)[1]:
                raise ValueError(
                    "The feature dimensionality of the train and test "
                    "data does not match train({}) != test({})".format(
                        np.shape(X_train)[1], np.shape(X_test)[1]
                    )
                )

        self._is_fitted = True

        return self

    def transform(
        self,
        X: SUPPORTED_FEAT_TYPES,
    ) -> Union[np.ndarray, spmatrix, pd.DataFrame]:
        """
        Validates and fit a categorical encoder (if needed) to the features.
        The supported data types are List, numpy arrays and pandas DataFrames.

        Parameters
        ----------
        X_train: SUPPORTED_FEAT_TYPES
            A set of features, whose categorical features are going to be
            transformed

        Return
        ------
        np.ndarray | spmatrix | pd.DataFrame:
            The transformed array
        """
        if not self._is_fitted:
            raise NotFittedError(
                "Cannot call transform on a validator that is not fitted"
            )

        # If a list was provided, it will be converted to pandas
        if isinstance(X, List):
            X_transformed, _ = self.list_to_dataframe(X)
        else:
            X_transformed = X

        # Check the data here so we catch problems on new test data
        self._check_data(X_transformed)

        # Sparse related transformations
        # Not all sparse format support index sorting
        if isinstance(X_transformed, spmatrix):
            if not isinstance(X_transformed, csr_matrix):
                self.logger.warning(
                    f"Sparse data provided is of type {type(X_transformed)} "
                    "yet Auto-Sklearn only support csr_matrix. Auto-sklearn "
                    "will convert the provided data to the csr_matrix format."
                )
                X_transformed = X_transformed.tocsr(copy=False)

            X_transformed.sort_indices()

        return X_transformed

    def _check_data(
        self,
        X: SUPPORTED_FEAT_TYPES,
    ) -> None:
        """
        Feature dimensionality and data type checks

        Parameters
        ----------
        X: SUPPORTED_FEAT_TYPES
            A set of features that are going to be validated (type and dimensionality)
            and a encoder fitted in the case the data needs encoding
        """
        # We consider columns that are all nan in a pandas frame as category
        if hasattr(X, "columns"):
            for column in cast(pd.DataFrame, X).columns:
                if X[column].isna().all():
                    X[column] = X[column].astype("category")

        if not isinstance(X, (np.ndarray, pd.DataFrame)) and not isinstance(
            X, spmatrix
        ):
            raise ValueError(
                "Auto-sklearn only supports Numpy arrays, Pandas DataFrames,"
                " scipy sparse and Python Lists, yet, the provided input is"
                " of type {}".format(type(X))
            )

        if self.data_type is None:
            self.data_type = type(X)

        if self.data_type != type(X):
            self.logger.warning(
                f"Auto-sklearn previously received features of type {self.data_type} "
                f"yet the current features have type {type(X)}. Changing the dtype "
                "of inputs to an estimator might cause problems"
            )

        # Do not support category/string numpy data. Only numbers
        if hasattr(X, "dtype"):
            if not np.issubdtype(X.dtype.type, np.number):  # type: ignore[union-attr]
                raise ValueError(
                    "When providing a numpy array to Auto-sklearn, the only valid"
                    f" dtypes are numerical ones. The provided data type {X.dtype.type}"
                    " is not supported."
                )

        # Then for Pandas, we do not support Nan in categorical columns
        if hasattr(X, "iloc"):
            # If entered here, we have a pandas dataframe
            X = cast(pd.DataFrame, X)

            dtypes = {col: X[col].dtype.name.lower() for col in X.columns}
            if len(self.dtypes) > 0:
                if self.dtypes != dtypes:
                    # To support list, we need to support object inference.
                    # In extreme cases, the train column might be all integer,
                    # and the test column might be float.
                    self.logger.warning(
                        "Changing the dtype of the features after fit() is "
                        "not recommended. Fit() method was called with "
                        "{} whereas the new features have {} as type".format(
                            self.dtypes,
                            dtypes,
                        )
                    )
            else:
                self.dtypes = dtypes

    def get_feat_type_from_columns(
        self,
        X: pd.DataFrame,
    ) -> Dict[Union[str, int], str]:
        """
        Returns a dictionary that maps pandas dataframe columns to a feature type.
        This feature type can be categorical, numerical or string

        Parameters
        ----------
        X: pd.DataFrame
            A set of features that are going to be validated (type and dimensionality
            checks) and a encoder fitted in the case the data needs encoding

        Returns
        -------
        feat_type:
            dictionary with column to feature type mapping
        """
        # Also, register the feature types for the estimator
        feat_type = {}

        # Make sure each column is a valid type
        for i, column in enumerate(X.columns):
            if is_sparse(X[column]):
                raise ValueError(
                    "Auto-sklearn does not yet support sparse pandas Series."
                    f" Please convert {column} to a dense format."
                )
            elif X[column].dtype.name in ["category", "bool"]:
                feat_type[column] = "categorical"
            elif X[column].dtype.name == "string":
                if self.allow_string_features:
                    feat_type[column] = "string"
                else:
                    feat_type[column] = "categorical"
                    warnings.warn(
                        f"you disabled text encoding column {column} will be "
                        f"encoded as category"
                    )
            # Move away from np.issubdtype as it causes
            # TypeError: data type not understood in certain pandas types
            elif not is_numeric_dtype(X[column]):
                if X[column].dtype.name == "object":
                    warnings.warn(
                        f"Input Column {column} has generic type object. "
                        f"Autosklearn will treat this column as string. "
                        f"Please ensure that this setting is suitable for your task.",
                        UserWarning,
                    )
                    if self.allow_string_features:
                        feat_type[column] = "string"
                    else:
                        feat_type[column] = "categorical"
                        warnings.warn(
                            f"you disabled text encoding column {column} will be"
                            f"encoded as category"
                        )
                elif pd.core.dtypes.common.is_datetime_or_timedelta_dtype(
                    X[column].dtype
                ):
                    raise ValueError(
                        "Auto-sklearn does not support time and/or date datatype as "
                        f"given in column {column}. Please convert the time "
                        " information to a numerical value first. One example on how to"
                        " do this can be found on "
                        " https://stats.stackexchange.com/questions/311494/"
                    )
                else:
                    raise ValueError(
                        "Input Column {} has unsupported dtype {}. "
                        "Supported column types are categorical/bool/numerical dtypes. "
                        "Make sure your data is formatted in a correct way, "
                        "before feeding it to Auto-Sklearn.".format(
                            column,
                            X[column].dtype.name,
                        )
                    )
            else:
                feat_type[column] = "numerical"
        return feat_type

    def list_to_dataframe(
        self,
        X_train: SUPPORTED_FEAT_TYPES,
        X_test: Optional[SUPPORTED_FEAT_TYPES] = None,
    ) -> Tuple[pd.DataFrame, Optional[pd.DataFrame]]:
        """
        Converts a list to a DataFrame. In this process, column types are inferred.

        If test data is provided, we proactively match it to train data

        Parameters
        ----------
        X_train: SUPPORTED_FEAT_TYPES
            A set of features that are going to be validated (type and dimensionality
            checks) and a encoder fitted in the case the data needs encoding

        X_test: Optional[SUPPORTED_FEAT_TYPES]
            A hold out set of data used for checking

        Returns
        -------
        Union[pd.DataFrame, pd.DataFrame]:
            transformed (train, test) data from list to pandas DataFrame
        """
        # If a list was provided, it will be converted to pandas
        X_train = pd.DataFrame(data=X_train).convert_dtypes()

        # Store the dtypes and use in case of re-fit
        if len(self.dtypes) == 0:
            self.dtypes = {
                col: X_train[col].dtype.name.lower() for col in X_train.columns
            }
        else:
            for col in X_train.columns:
                # Try to convert to the original dtype used to fit the validator
                # But also be robust to extreme cases (for example, the train data for a
                # column was all np.int-like and the test data is np.float-type)
                try:
                    X_train[col] = X_train[col].astype(self.dtypes[col])
                except Exception as e:
                    self.logger.warning(
                        f"Failed to format column {col} as {self.dtypes[col]}: {e}"
                    )
                    self.dtypes[col] = X_train[col].dtype.name.lower()

        self.logger.warning(
            "The provided feature types to autosklearn are of type list."
            "Features have been interpreted as: {}".format(
                [(col, t) for col, t in zip(X_train.columns, X_train.dtypes)]
            )
        )
        if X_test is not None:
            if not isinstance(X_test, List):
                self.logger.warning(
                    "Train features are a list while the provided test data"
                    "is {}. X_test will be casted as DataFrame.".format(type(X_test))
                )
            X_test = pd.DataFrame(data=X_test)
            for col in X_test.columns:
                try:
                    X_test[col] = X_test[col].astype(self.dtypes[col])
                except Exception as e:
                    self.logger.warning(
                        f"Failed to format column {col} as {self.dtypes[col]}: {e}"
                    )
                    self.dtypes[col] = X_test[col].dtype.name.lower()

        return X_train, X_test

redpajama_set_name: RedPajamaGithub


text:
<?php
/**
 * Created by PhpStorm.
 * User: drodriguez
 * Date: 09-06-15
 * Time: 04:57 PM
 */

namespace data_access;

/**
 * Class AppDALFactory
 * Provee de un metodo para obtener una instancia de IAppDAL con la configuración de acceso
 * a base de datos determinado en config.php
 * @package data_access
 */
class AppDALFactory {
    private static $Instance;

    /**
     * @return IAppDAL
     */
    public static function instance()
    {
        if(!isset(self::$Instance))
        {
            $classString = 'data_access\\'.DB_TYPE.'\\AppDAL';
            self::$Instance =  new $classString();
        }
        return self::$Instance;
    }
}


text:
===========
Example app
===========

::

    cd tests && ./manage.py runserver

Username and password for admin are 'administrator', 'password'.


text:
require 'rails_helper'

describe ExecuteService do
  after(:all) do
    Association.destroy_all
    Invoice.destroy_all
    Rule.destroy_all
    Transformation.destroy_all
  end

  it 'should execute transactions' do
    rand_array_of_models(:transaction).each do |txm|
      ams = rand_array_of_models(:association, transact: txm).map do |am|
        am.update_attributes(rule: create(:rule), transformation: create(:transformation))
        am
      end

      ims = rand_array_of_models(:invoice, transact: txm)

      ams.each do |am|
        ims.each do |im|
          expect(InterpretService).to receive(:execute).with(im.id, am.rule.id, am.transformation.id)
        end
      end

      ExecuteService.execute(txm.id)
    end
  end
end


text:
<?php

namespace Bs\UserBundle\Repository;

use Bs\UserBundle\Entity\User;
use Doctrine\ORM\EntityRepository;
use Symfony\Bridge\Doctrine\Security\User\UserLoaderInterface;

class UserRepository extends EntityRepository implements UserLoaderInterface
{
    public function loadUserByUsername($username)
    {
        $query = $this->createQueryBuilder('u')
            ->where('u.username = :username OR u.email = :Email')
            ->setParameter('username', $username)
            ->setParameter('Email', $username)
            ->getQuery()
            ->getOneOrNullResult();

        return $query;
    }

    /**
     * @param $filter
     * @return User[]
     */
    public function findFilter($filter)
    {
        $stations = $this->createQueryBuilder('u')
            ->where('u.name LIKE :filter')
            ->orWhere('u.email LIKE :filter')
            ->orWhere('u.username LIKE :filter')
            ->setParameter('filter', '%' . $filter . '%')
            ->getQuery()
            ->getResult();

        return $stations;
    }
}


text:
import os

import pytest

from updot import platform

# pylint: disable=protected-access

def test__relative_paths__return_false():
    """Relative paths should always return false"""

    assert not os.path.isabs('./path/to/thing')
    assert not os.path.isabs('../path/to/thing')
    assert not os.path.isabs('path/to/thing')

if platform.WINDOWS:
    def test__windows_rooted_paths_on_windows__return_true():
        """Windows-specific rooted paths always return true"""

        assert os.path.isabs('c:/abs/path.txt')
        assert os.path.isabs('//unc/server/path')

    def test__posix_rooted_paths_on_windows__return_false():
        """Posix-style rooted paths should always return false on Windows"""

        assert not os.path.isabs('/path/to/thing')
        assert not os.path.isabs(R'\path\to\thing')

if platform.POSIX:
    def test__posix_rooted_paths_on_posix__return_true():
        """Posix-style rooted paths should always return true on posix"""

        assert os.path.isabs('/path/to/thing')

if __name__ == "__main__":
    pytest.main(__file__)


text:
var schema    = require('../schema').tables,
    _         = require('lodash'),
    validator = require('validator'),
    when      = require('when'),
    errors    = require('../../errors'),

    validateSchema,
    validateSettings,
    validate;

// Provide a few custom validators
//
validator.extend('empty', function (str) {
    return _.isEmpty(str);
});

validator.extend('notContains', function (str, badString) {
    return !_.contains(str, badString);
});

// Validation validation against schema attributes
// values are checked against the validation objects
// form schema.js
validateSchema = function (tableName, model) {
    var columns = _.keys(schema[tableName]),
        validationErrors = [];

    _.each(columns, function (columnKey) {
        var message = '';
        // check nullable
        if (model.hasOwnProperty(columnKey) && schema[tableName][columnKey].hasOwnProperty('nullable')
                && schema[tableName][columnKey].nullable !== true) {
            if (validator.isNull(model[columnKey]) || validator.empty(model[columnKey])) {
                message = 'Value in [' + tableName + '.' + columnKey + '] cannot be blank.';
                validationErrors.push(new errors.ValidationError(message, tableName + '.' + columnKey));
            }
        }
        // TODO: check if mandatory values should be enforced
        if (model[columnKey]) {
            // check length
            if (schema[tableName][columnKey].hasOwnProperty('maxlength')) {
                if (!validator.isLength(model[columnKey], 0, schema[tableName][columnKey].maxlength)) {
                    message = 'Value in [' + tableName + '.' + columnKey + '] exceeds maximum length of '
                        + schema[tableName][columnKey].maxlength + ' characters.';
                    validationErrors.push(new errors.ValidationError(message, tableName + '.' + columnKey));
                }
            }

            //check validations objects
            if (schema[tableName][columnKey].hasOwnProperty('validations')) {
                validationErrors.concat(validate(model[columnKey], columnKey, schema[tableName][columnKey].validations));
            }

            //check type
            if (schema[tableName][columnKey].hasOwnProperty('type')) {
                if (schema[tableName][columnKey].type === 'integer' && !validator.isInt(model[columnKey])) {
                    message = 'Value in [' + tableName + '.' + columnKey + '] is no valid integer.';
                    validationErrors.push(new errors.ValidationError(message, tableName + '.' + columnKey));
                }
            }
        }
    });

    if (validationErrors.length !== 0) {
        return when.reject(validationErrors);
    }
};

// Validation for settings
// settings are checked against the validation objects
// form default-settings.json
validateSettings = function (defaultSettings, model) {
    var values = model.toJSON(),
        matchingDefault = defaultSettings[values.key];

    if (matchingDefault && matchingDefault.validations) {
        return validate(values.value, values.key, matchingDefault.validations);
    }
};

// Validate default settings using the validator module.
// Each validation's key is a method name and its value is an array of options
//
// eg:
//      validations: { isUrl: true, isLength: [20, 40] }
//
// will validate that a setting's length is a URL between 20 and 40 chars.
//
// If you pass a boolean as the value, it will specify the "good" result. By default
// the "good" result is assumed to be true.
//
// eg:
//      validations: { isNull: false }  // means the "good" result would
//                                      // fail the `isNull` check, so
//                                      // not null.
//
// available validators: https://github.com/chriso/validator.js#validators
validate = function (value, key, validations) {
    var validationErrors = [];
    _.each(validations, function (validationOptions, validationName) {
        var goodResult = true;

        if (_.isBoolean(validationOptions)) {
            goodResult = validationOptions;
            validationOptions = [];
        } else if (!_.isArray(validationOptions)) {
            validationOptions = [validationOptions];
        }

        validationOptions.unshift(value);

        // equivalent of validator.isSomething(option1, option2)
        if (validator[validationName].apply(validator, validationOptions) !== goodResult) {
            validationErrors.push(new errors.ValidationError('Settings validation (' + validationName + ') failed for ' + key, key));
        }

        validationOptions.shift();
    }, this);

    if (validationErrors.length !== 0) {
        return when.reject(validationErrors);
    }
};

module.exports = {
    validateSchema: validateSchema,
    validateSettings: validateSettings
};


text:
Simple Python Client for [Microsoft Cognitive Services](https://www.microsoft.com/cognitive-services).

## Installation

```
pip install pyoxford
```

And you have to prepare Cognitive Service account to use each services.

## Speech APIs

```python
import pyoxford

text = "welcome to microsoft oxford speech api"
api = pyoxford.speech("your_client_id", "your_client_secret")

# text to speech (.wav file)
binary = api.text_to_speech(text)
with open("voice.wav", "wb") as f:
    f.write(binary)

# speech to text
recognized = api.speech_to_text("voice.wav")

if text == recognized:
    print("success!!")
```

see also official document.

* [text to speech](https://www.projectoxford.ai/doc/speech/REST/Output)
* [speech to text](https://www.projectoxford.ai/doc/speech/REST/Recognition)

## Vision APIs

### Analyze

```python
import pyoxford

api = pyoxford.vision("your_primary_key")
result = api.analyze("https://oxfordportal.blob.core.windows.net/vision/Analysis/4.jpg")

for c in result.categories:
    print(c.name)

```

see also official document.

* [Analyze an image](https://www.projectoxford.ai/doc/vision/visual-features)
* [Computer Vision API #Analyze an image](https://dev.projectoxford.ai/docs/services/54ef139a49c3f70a50e79b7d/operations/550a323849c3f70b34ba2f8d)

### OCR

```python
import pyoxford

api = pyoxford.vision("your_primary_key")
result = api.ocr("https://oxfordportal.blob.core.windows.net/vision/OpticalCharacterRecognition/1.jpg")

doc = result.to_document()
for par in doc:
    print("\n".join(par))
```

see also official document.

* [Optical Character Recognition](https://www.projectoxford.ai/doc/vision/OCR)
* [Computer Vision API #OCR](https://dev.projectoxford.ai/docs/services/54ef139a49c3f70a50e79b7d/operations/5527970549c3f723cc5363e4)

## Translator API

[Translator API](https://datamarket.azure.com/dataset/bing/microsofttranslator) is not project oxford's api, but it is very useful to use with speech api and so on.
To use this API, you have to do step1 & step2 of [Get started](http://www.microsoft.com/en-us/translator/getstarted.aspx).

```python
import pyoxford

api = pyoxford.translator("your_client_id", "your_client_secret")
result = api.translate("My name is John.", "ja")

if "私の名前はジョンです。" == result:
    print("Well translated!!")
```


text:
package br.cefetrj.sagitarii.metrics;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

import br.cefetrj.sagitarii.misc.PathFinder;

public class MetricController {
	private static MetricController instance;
	private List<IMetricEntity> entities;

	public void saveMetrics() {
		try {
			String path = PathFinder.getInstance().getPath() + "/metrics/";
			File newFile = new File(path);
			newFile.mkdirs();
			for ( IMetricEntity entity : getEntities() ) {
				entity.saveImage( path );
			}
		} catch ( Exception e ) {
			//e.printStackTrace();
		}
	}

	public IMetricEntity addHitEntity( String name, MetricType type ) {
		IMetricEntity entity = new MetricHitEntity( name, type );
		entities.add( entity );
		return entity;
	}

	public IMetricEntity addValueEntity( String name, MetricType type ) {
		IMetricEntity entity = new MetricValueEntity( name, type );
		entities.add( entity );
		return entity;
	}

	public void reset() {
		entities = new ArrayList<IMetricEntity>();
	}

	public List<IMetricEntity> getEntities() {
		return new ArrayList<IMetricEntity>( entities );
	}

	public static MetricController getInstance() {
		if( instance == null ) {
			instance = new MetricController();
		}
		return instance;
	}

	private MetricController() {
		entities = new ArrayList<IMetricEntity>();
	}

	public void computeMetrics() {
		for ( IMetricEntity entity : getEntities() ) {
			entity.calc();
		}

	}

	public IMetricEntity getEntity( String name ) {
		for ( IMetricEntity entity : getEntities() ) {
			if ( entity.getName().equals( name ) ) {
				return entity;
			}
		}
		return null;
	}

	public void setTimeSpent( String name, double time ) {
		for ( IMetricEntity entity : getEntities() ) {
			if ( entity.getName().equals( name ) ) {
				entity.setTimeSpent(time);
			}
		}
	}

	public synchronized void hit( String name, MetricType type ) {
		boolean found = false;
		for ( IMetricEntity entity : getEntities() ) {
			if ( entity.getName().equals( name ) ) {
				( (MetricHitEntity)entity ).hit();
				found = true;
				break;
			}
		}
		if ( !found ) {
			IMetricEntity entity = addHitEntity(name,type);
			( (MetricHitEntity)entity ).hit();
		}
	}

	public synchronized void set(double value, String name, MetricType type ) {
		boolean found = false;
		for ( IMetricEntity entity : getEntities() ) {
			if ( entity.getName().equals( name ) ) {
				( (MetricValueEntity)entity ).set(value);
				found = true;
				break;
			}
		}
		if ( !found ) {
			IMetricEntity entity = addValueEntity(name,type);
			( (MetricValueEntity)entity ).set(value);
		}
	}

}


text:
import math, random, sys, copy

#>>> Our Objects and Functions

# Initially we deal with 30 notes that construct the main region of the guitar
# fret board. These will be numbered 0-29, with 0 indicating the note E2 and
# 29 indicating A4. Each increment of a number indicates an increase of one
# semi-tone, i.e. E->F (0->1) or C->C# (8->9).
# (Notes from here on out will be indicated as their given absolute note
# numbers, or ANNs.)

ANNconv = ['E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb',
           'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb',
           'E', 'F', 'Gb', 'G', 'Ab', 'A', 'Bb', 'B', 'C', 'Db', 'D', 'Eb']

# The guitar has 6 strings tuned so that the 5th fret of one string is the same
# pitch as the open string directly adjacent to it. The one exception to this
# is the 3rd string whose adjacent string is tuned to its fourth fret.
# We hope to capture possible note combinations and to avoid attempting to play
# two notes on the same string. As such, we will only model with the notes that
# exist within the first four frets on each string, (with the exception of the
# 3rd string where we only go to the third fret.)

#>> Absolute Note Number to Tabulature Translator Function

# It should be noted here that the first string contains the highest notes, and
# subsequently higher strings contain subsequently lower notes. This is an
# unavoidable concequence of the traditional naming scheme. This simply means
# that when translating ANN to TAB we must start at the end of the list
# and move towards the front.
# TAB is mainly used for outputting readable note structures. We will only need
# it for performing output and checking that there are no string overlaps.

def ANNtoTAB(string, ANN):
    # We import two ints that will change to the appropriate numbers.
    string = 5
    # We reduce the ANN to a fret number for a given string.
    while ANN > 4:
        # We work backwards from the 6th string.
        string -= 1
        if string != 2:
            ANN -= 5
        else:
            ANN -= 4
    # Here we take the exception to the loop and manually change it.
    if ((ANN == 4) and (string == 2)):
        ANN = 0
        string = 1
    if ANN > 4:
        print "ERROR!!!"
    return [string,ANN]

#>> Chord Fitting Function

# For a given set of notes, we would like to give a number of potential chords
# that can be written. The length of such list is inversely proportional to
# the fitness of such notes, unless no chords can be found.
# We initially define all possible three note chords with their individual
# distances, and from pairwise distances we infer their relative root.
# For the major triad, whose distances are 0-4-7, we store the relative
# distances as 0,4,3 and 7 semi-tones. If a two note chord is 3 semi-tones
# apart, they could be part of the major triad located 4 semi-tones below the
# lowest note.

chordStruct = {'E':['E','Ab','B'],'Em':['E','G','B'],'F':['F','A','C'],
               'Fm':['F','Ab','C'],'Gb':['Gb','Bb','Db'],'Gbm':['Gb','A','Db'],
               'G':['G','B','D'],'Gm':['G','Bb','D'],'Ab':['Ab','C','Eb'],
               'Abm':['Ab','B','Eb'],'A':['A','Db','E'],'Am':['A','C','E'],
               'Bb':['Bb','D','F'],'Bbm':['Bb','Db','F'],'B':['B','Eb','Gb'],
               'Bm':['B','D','Gb'],'C':['C','E','G'],'Cm':['C','Eb','G'],
               'Db':['Db','F','Ab'],'Dbm':['Db','E','Ab'],'D':['D','Gb','A'],
               'Dm':['D','F','A'],'Eb':['Eb','G','Bb'],'Ebm':['Eb','Gb','Bb']}

# There can only be 1 or 0 chords for a 3 note chord. For a 2 note chord, there
# are a potential of 0 to 2 potential chords. For 1 note, all chords containing
# that note are considered, which totals at 15 different chords.

def ChordFit(noteList):
    nameList = []
    for note in noteList:
        nameList.append(ANNconv[note])
    i = len(nameList)
    chordList = []
    """if (len(noteList) == 1):
        for key in chordStruct.keys():
            inChord = False
            if ((noteList[0] == chordStruct[key][0]) or
                (noteList[0] == chordStruct[key][1])):
                inChord = True
            if (inChord == True):
                chordList.append(key)
    else:"""
    if True:
        for key in chordStruct.keys():
            inChord = True
            for note in nameList:
                if note not in chordStruct[key]:
                    inChord = False
            if (inChord == True):
                chordList.append(key)
    return chordList

#>> Chord Object

# We would like to define a give chord by its TAB format. Each given string
# will have a default NULL value of -1, and a fret range of 0-4 (or 0-3 for
# string 3.) This will be the output value for printing results.
# We will also have a list of the ANNs for easy calculation,
# and a list of potential chord memberships.

class chord:
    def __init__(self, noteList=[]):
        self.valid = True
        self.noteList = noteList
        self.length = len(self.noteList)
        self.tabList = [-1,-1,-1,-1,-1,-1]
        self.chordList = []
        self.score = 0
        self.updateTAB()

    # We translate the ANNs to TAB to fill our empty TAB list
    def updateTAB(self):
        self.tabList = [-1,-1,-1,-1,-1,-1]
        #print self.noteList,'\t',
        for note in self.noteList:
            string = 0
            string = ANNtoTAB(string, note)
            if (string[1] > 4):
                print "ERROR: Invalid Notes"
            if (self.tabList[string[0]] == -1):
                self.tabList[string[0]] = string[1]
            else:
                self.noteList.remove(note)
        #print self.tabList

    # This will only output the notes in letter format for debugging purposes
    def __str__(self):
        if (self.valid == False):
            return "ERROR: Invalid Chord"
        self.out = ""
        for note in self.noteList:
            self.out += ANNconv[note] + ','
        return self.out

    # This output function will output TAB frets for a specific string
    def str_out(self, string):
        self.updateTAB()
        if (self.tabList[string] > 4):
            print "ERROR: Invalid Notes"
        if (self.valid == False):
            print "X-",
        elif (self.tabList[string] == -1):
            print "--",
        else:
            outstring = str(self.tabList[string])
            outstring += '-'
            print outstring,

    # We would like to have a function for generating new, completely random
    # sequences from scratch.
    def randomize(self):
        self.noteList = []
        self.tabList = [-1,-1,-1,-1,-1,-1]
        self.chordList = []
        self.score = 0
        length = random.randint(1,3)
        #print length,
        while (length > 0):
            newNote = random.randint(0,29)
            #print "[",newNote,"]"
            string = 0
            string = ANNtoTAB(string, newNote)
            if (self.tabList[string[0]] == -1):
                self.tabList[string[0]] = string[1]
                self.noteList.append(newNote)
                length -= 1
                #print length,
        #print
        self.length = len(self.noteList)

    # For the individual score of the chord we look at chord specificity.
    # The fewer number of possible chord participants, the better 'fit' and
    # so the higher score, for a maximum of 6.
    def score_self(self):
        self.chordList = ChordFit(self.noteList)
        if (len(self.chordList) == 0 ):
            self.score = -5
        else:
            self.score = 2*(6 - len(self.chordList))
        return self.score

    # For the purpose of scoring transitions, we would like to be able to
    # obtain the potential memberships that the chord contains.
    def chords(self):
        return self.chordList

    # Mutations
    def mutate(self, percent):
        chance = random.randint(0,1000)
        if percent > chance:
            mute = random.randint(1,4)
            if (mute == 1) and (self.length < 3): #Insertion
                newNote = random.randint(0,29)
                stringNote = newNote
                string = 0
                ANNtoTAB(string, stringNote)
                if (self.tabList[string] == -1):
                    self.tabList[string] = newNote
                    self.noteList.append(newNote)
                self.length = len(self.noteList)
            if (mute == 2) and (self.length > 1): #Deletion
                out = random.randint(0,len(self.noteList)-1)
                self.noteList.pop(out)
                self.length = len(self.noteList)
                self.updateTAB()
            if (mute == 3):                       # Transition
                point = random.randint(0,len(self.noteList)-1)
                shift = random.randint(-1,1)
                note = self.noteList[point]
                note += shift
                if (note < 0):
                    note = 0
                if (note > 29):
                    note = 29
                self.noteList[point] = note
                self.updateTAB()
            if (mute == 4):                        # Chord Shift
                shift = random.randint(-1,1)
                for i in range(0,len(self.noteList)):
                    note = self.noteList[i]
                    note += shift
                    if (note < 0):
                        note = 0
                    if (note > 29):
                        note = 29
                    self.noteList[i] = note
                self.updateTAB()

#>> Riff Object
# Our Riff Object will contain a number of chords

class riff:
    def __init__(self, chordList=[]):
        self.chordList = chordList
        self.length = len(chordList)
        self.score = 0

    def str_out(self):
        for i in range(0,6):
            for chord in self.chordList:
                chord.str_out(i)
            print "\n"
        print self.score

    def score_self(self):
        self.score = 10 # This initialy 10 is to counter the -10 from not
                        # having a previous chord to compare
        prevChords = []
        for this in self.chordList:
            self.score += this.score_self()
            flag = False
            for prev in prevChords:
                for now in this.chords():
                    if chordStruct[now][0] in chordStruct[prev]:
                        flag = True
            prevChords = this.chords()
            if (flag == True):
                self.score += 10
            else:
                self.score -= 10
        return self.score

    def randomize(self):
        self.score = 0
        self.chordList = []
        limit = random.randint(3,10)
        for i in range(0,limit):
            new = chord()
            new.randomize()
            self.chordList.append(new)
        self.score_self()

    def mutate(self, percent):
        for chord in self.chordList:
            chord.mutate(percent)
            if (len(chord.noteList) == 0):
                self.chordList.remove(chord)
        chance = random.randint(0,1000)

    def splice(self, other):
        size = [len(self.chordList), len(other.chordList)]
        size.sort()
        mute = random.randint(3,size[0])
        newList = self.chordList[0:mute]
        newList += other.chordList[mute:]
        newriff = riff(newList)
        return newriff

    def shift(self):
        mute = random.randint(0,len(self.chordList))
        newList = self.chordList[mute:]
        newList += self.chordList[0:mute]
        self.chordList = newList

# From these definitions of riffs and chords, we will now construct our
# genetic algorithm. We will produce a population of riffs and from there
# we will shift for the top scoring riffs and then mutate the resulting
# population.

def sort(Pop, flag = False):
    top = Pop[0]
    bot = Pop[0]
    bad = Pop[0].score_self()
    score = Pop[0].score_self()
    for i in Pop:
        if i.score_self() > score:
            top = i
            score = top.score_self()
        elif i.score_self() < bad:
            bot = i
            bad = bot.score_self()
    total = 0
    if (flag == True):
        top.str_out()
        bot.str_out()
    for i in Pop:
        addition = (i.score_self() - bad)
        total += addition
    return [total, bad]

def topsift(Pop, old):
    top = old
    score = top.score_self()
    for i in Pop:
        if i.score_self() > score:
            top = i
            score = top.score_self
    return top

Population = []
for i in range(0,500):
    new = riff()
    new.randomize()
    Population.append(new)

best = riff()
best.randomize()

for i in range(0,101):
    print "[",i,"]"
    flag = False
    if (i%10 == 0):
        flag = True
    best = topsift(Population, best)
    split = sort(Population, flag)
    top = split[0] - 5
    bot = split[1]
    newPop = []
    for j in range(0,250):
        x = random.randint(0,top)
        point = -1
        while (x > 0):
            point += 1
            out = Population[point].score_self()
            x -= (out - bot)
        newCopy = copy.deepcopy(Population[point])
        newCopy.mutate((200-(2*i)))
        newPop.append(newCopy)
    for j in range(0,125):
        x = random.randint(0,top)
        y = random.randint(0,top)
        xpoint = -1
        ypoint = -1
        while (x > 0):
            xpoint += 1
            out = Population[xpoint].score_self()
            x -= (out - bot)
        while (y > 0):
            ypoint += 1
            out = Population[ypoint].score_self()
            y -= (out - bot)
        newCopy = Population[xpoint].splice(Population[ypoint])
        deeperCopy = copy.deepcopy(newCopy)
        newPop.append(deeperCopy)
    for j in range(0,125):
        x = random.randint(0,top)
        point = -1
        while (x > 0):
            point += 1
            if point > 500:
                point = 500
                x = -1
            out = Population[point].score_self()
            x -= (out - bot)
        newCopy = Population[point]
        deeperCopy = copy.deepcopy(newCopy)
        deeperCopy.shift()
        newPop.append(deeperCopy)
    Population = newPop

best.str_out()
for chord in best.chordList:
    print chord.chordList


text:
package com.redkite.plantcare.common.dto;

import lombok.Data;

import org.hibernate.validator.constraints.NotBlank;

import java.time.LocalDateTime;

import javax.validation.constraints.NotNull;

@Data
public class LogDataRequest {

  @NotNull
  private Long sensorId;

  private String dataType;

  @NotBlank
  private Integer value;

  private LocalDateTime logTime;
}


text:
% t_TestTutorials
%
%   Quick run through class tutorial files to verify that they all run
%
% Copyright ImagEval Consultants, LLC, 2010.

%% Run through all the tutorial files
t_opticsImageFormation
disp('ImageFormation confirmed');
clear all; close all

%%
t_colorMatching
disp('ColorMatching');
clear all; close all

%%
t_colorSpectrum
disp('Spectrum');
clear all; close all

%%
t_metrics
disp('Metrics confirmed');
clear all; close all

%%
t_imageJPEGmonochrome
disp('JPEG_bw confirmed')
clear all; close all

%%
t_imageJPEGcolor
disp('JPEG_color confirmed')
clear all; close all

%%
t_sensorEstimation
disp('Sensor Estimation confirmed')
clear all; close all

%%
t_displayRendering
disp('Rendering confirmed')
clear all; close all

%%
t_printingHalftone
disp('Halftone confirmed')
clear all; close all

%% END


text:
/* $Id: logcom.cpp $ */
/** @file
 * IPRT - Logging to Serial Port.
 */

/*
 * Copyright (C) 2006-2015 Oracle Corporation
 *
 * This file is part of VirtualBox Open Source Edition (OSE), as
 * available from http://www.virtualbox.org. This file is free software;
 * you can redistribute it and/or modify it under the terms of the GNU
 * General Public License (GPL) as published by the Free Software
 * Foundation, in version 2 as it comes in the "COPYING" file of the
 * VirtualBox OSE distribution. VirtualBox OSE is distributed in the
 * hope that it will be useful, but WITHOUT ANY WARRANTY of any kind.
 *
 * The contents of this file may alternatively be used under the terms
 * of the Common Development and Distribution License Version 1.0
 * (CDDL) only, as it comes in the "COPYING.CDDL" file of the
 * VirtualBox OSE distribution, in which case the provisions of the
 * CDDL are applicable instead of those of the GPL.
 *
 * You may elect to license modified versions of this file under the
 * terms and conditions of either the GPL or the CDDL or both.
 */

/*******************************************************************************
*   Defined Constants And Macros                                               *
*******************************************************************************/
#ifndef IPRT_UART_BASE
/** The port address of the COM port to log to.
 *
 * To override the default (COM1) append IPRT_UART_BASE=0xWXYZ to DEFS in your
 * LocalConfig.kmk. Alternatively you can edit this file, but the don't forget
 * to also update the default found in VBox/asmdefs.h.
 *
 * Standard port assignments are: COM1=0x3f8, COM2=0x2f8, COM3=0x3e8, COM4=0x2e8.
 */
# define IPRT_UART_BASE 0x3f8
#endif

/*******************************************************************************
*   Header Files                                                               *
*******************************************************************************/
#include <iprt/log.h>
#include "internal/iprt.h"

#include <iprt/asm.h>
#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86) /** @todo consider fixing the config instead. */
# include <iprt/asm-amd64-x86.h>
#endif
#include <iprt/stdarg.h>
#include <iprt/string.h>

/*******************************************************************************
*   Internal Functions                                                         *
*******************************************************************************/
static DECLCALLBACK(size_t) rtLogComOutput(void *pv, const char *pachChars, size_t cbChars);

/**
 * Prints a formatted string to the serial port used for logging.
 *
 * @returns Number of bytes written.
 * @param   pszFormat   Format string.
 * @param   ...         Optional arguments specified in the format string.
 */
RTDECL(size_t) RTLogComPrintf(const char *pszFormat, ...)
{
    va_list     args;
    size_t      cb;
    va_start(args, pszFormat);
    cb = RTLogComPrintfV(pszFormat, args);
    va_end(args);

    return cb;
}
RT_EXPORT_SYMBOL(RTLogComPrintf);

/**
 * Prints a formatted string to the serial port used for logging.
 *
 * @returns Number of bytes written.
 * @param   pszFormat   Format string.
 * @param   args        Optional arguments specified in the format string.
 */
RTDECL(size_t) RTLogComPrintfV(const char *pszFormat, va_list args)
{
    return RTLogFormatV(rtLogComOutput, NULL, pszFormat, args);
}
RT_EXPORT_SYMBOL(RTLogComPrintfV);

/**
 * Callback for RTLogFormatV which writes to the com port.
 * See PFNLOGOUTPUT() for details.
 */
static DECLCALLBACK(size_t) rtLogComOutput(void *pv, const char *pachChars, size_t cbChars)
{
    NOREF(pv);
    if (cbChars)
        RTLogWriteCom(pachChars, cbChars);
    return cbChars;
}

/**
 * Write log buffer to COM port.
 *
 * @param   pach        Pointer to the buffer to write.
 * @param   cb          Number of bytes to write.
 */
RTDECL(void) RTLogWriteCom(const char *pach, size_t cb)
{
#if defined(RT_ARCH_AMD64) || defined(RT_ARCH_X86)
    const uint8_t *pu8;
    for (pu8 = (const uint8_t *)pach; cb-- > 0; pu8++)
    {
        register unsigned cMaxWait;
        register uint8_t  u8;

        /* expand \n -> \r\n */
        if (*pu8 == '\n')
            RTLogWriteCom("\r", 1);

        /* Check if port is ready. */
        cMaxWait = ~0U;
        do
        {
            u8 = ASMInU8(IPRT_UART_BASE + 5);
            cMaxWait--;
        } while (!(u8 & 0x20) && u8 != 0xff && cMaxWait);

        /* write */
        ASMOutU8(IPRT_UART_BASE, *pu8);
    }
#else
    /* PORTME? */
#endif
}
RT_EXPORT_SYMBOL(RTLogWriteCom);


text:
<Global.Microsoft.VisualBasic.CompilerServices.DesignerGenerated()> _
Partial Class Form1
    Inherits System.Windows.Forms.Form

    'Form overrides dispose to clean up the component list.
    <System.Diagnostics.DebuggerNonUserCode()> _
    Protected Overrides Sub Dispose(ByVal disposing As Boolean)
        Try
            If disposing AndAlso components IsNot Nothing Then
                components.Dispose()
            End If
        Finally
            MyBase.Dispose(disposing)
        End Try
    End Sub

    'Required by the Windows Form Designer
    Private components As System.ComponentModel.IContainer

    'NOTE: The following procedure is required by the Windows Form Designer
    'It can be modified using the Windows Form Designer.
    'Do not modify it using the code editor.
    <System.Diagnostics.DebuggerStepThrough()> _
    Private Sub InitializeComponent()
        Dim resources As System.ComponentModel.ComponentResourceManager = New System.ComponentModel.ComponentResourceManager(GetType(Form1))
        Me.Header = New System.Windows.Forms.Label
        Me.Label1 = New System.Windows.Forms.Label
        Me.Label2 = New System.Windows.Forms.Label
        Me.Label3 = New System.Windows.Forms.Label
        Me.Label4 = New System.Windows.Forms.Label
        Me.Label5 = New System.Windows.Forms.Label
        Me.Label6 = New System.Windows.Forms.Label
        Me.Label7 = New System.Windows.Forms.Label
        Me.Label8 = New System.Windows.Forms.Label
        Me.Label9 = New System.Windows.Forms.Label
        Me.Button20 = New System.Windows.Forms.Button
        Me.Label10 = New System.Windows.Forms.Label
        Me.Label11 = New System.Windows.Forms.Label
        Me.Button21 = New System.Windows.Forms.Button
        Me.Label12 = New System.Windows.Forms.Label
        Me.Label13 = New System.Windows.Forms.Label
        Me.Button1 = New System.Windows.Forms.Button
        Me.Button19 = New System.Windows.Forms.Button
        Me.SuspendLayout()
        '
        'Header
        '
        Me.Header.AutoSize = True
        Me.Header.BackColor = System.Drawing.Color.Transparent
        Me.Header.Font = New System.Drawing.Font("Calibri", 18.25!)
        Me.Header.ForeColor = System.Drawing.Color.White
        Me.Header.Location = New System.Drawing.Point(12, 9)
        Me.Header.Name = "Header"
        Me.Header.Size = New System.Drawing.Size(216, 31)
        Me.Header.TabIndex = 1
        Me.Header.Text = "TicTacToe - 2 spiller"
        '
        'Label1
        '
        Me.Label1.BackColor = System.Drawing.Color.Transparent
        Me.Label1.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Label1.Font = New System.Drawing.Font("Calibri", 30.0!)
        Me.Label1.Location = New System.Drawing.Point(144, 61)
        Me.Label1.Name = "Label1"
        Me.Label1.Size = New System.Drawing.Size(45, 45)
        Me.Label1.TabIndex = 31
        '
        'Label2
        '
        Me.Label2.BackColor = System.Drawing.Color.Transparent
        Me.Label2.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Label2.Font = New System.Drawing.Font("Calibri", 30.0!)
        Me.Label2.Location = New System.Drawing.Point(187, 61)
        Me.Label2.Name = "Label2"
        Me.Label2.Size = New System.Drawing.Size(45, 45)
        Me.Label2.TabIndex = 32
        '
        'Label3
        '
        Me.Label3.BackColor = System.Drawing.Color.Transparent
        Me.Label3.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Label3.Font = New System.Drawing.Font("Calibri", 30.0!)
        Me.Label3.Location = New System.Drawing.Point(229, 61)
        Me.Label3.Name = "Label3"
        Me.Label3.Size = New System.Drawing.Size(45, 45)
        Me.Label3.TabIndex = 33
        '
        'Label4
        '
        Me.Label4.BackColor = System.Drawing.Color.Transparent
        Me.Label4.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Label4.Font = New System.Drawing.Font("Calibri", 30.0!)
        Me.Label4.Location = New System.Drawing.Point(144, 106)
        Me.Label4.Name = "Label4"
        Me.Label4.Size = New System.Drawing.Size(45, 45)
        Me.Label4.TabIndex = 34
        '
        'Label5
        '
        Me.Label5.BackColor = System.Drawing.Color.Transparent
        Me.Label5.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Label5.Font = New System.Drawing.Font("Calibri", 30.0!)
        Me.Label5.Location = New System.Drawing.Point(187, 106)
        Me.Label5.Name = "Label5"
        Me.Label5.Size = New System.Drawing.Size(45, 45)
        Me.Label5.TabIndex = 35
        '
        'Label6
        '
        Me.Label6.BackColor = System.Drawing.Color.Transparent
        Me.Label6.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Label6.Font = New System.Drawing.Font("Calibri", 30.0!)
        Me.Label6.Location = New System.Drawing.Point(229, 106)
        Me.Label6.Name = "Label6"
        Me.Label6.Size = New System.Drawing.Size(45, 45)
        Me.Label6.TabIndex = 36
        '
        'Label7
        '
        Me.Label7.BackColor = System.Drawing.Color.Transparent
        Me.Label7.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Label7.Font = New System.Drawing.Font("Calibri", 30.0!)
        Me.Label7.Location = New System.Drawing.Point(144, 151)
        Me.Label7.Name = "Label7"
        Me.Label7.Size = New System.Drawing.Size(45, 45)
        Me.Label7.TabIndex = 37
        '
        'Label8
        '
        Me.Label8.BackColor = System.Drawing.Color.Transparent
        Me.Label8.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Label8.Font = New System.Drawing.Font("Calibri", 30.0!)
        Me.Label8.Location = New System.Drawing.Point(187, 151)
        Me.Label8.Name = "Label8"
        Me.Label8.Size = New System.Drawing.Size(45, 45)
        Me.Label8.TabIndex = 38
        '
        'Label9
        '
        Me.Label9.BackColor = System.Drawing.Color.Transparent
        Me.Label9.BorderStyle = System.Windows.Forms.BorderStyle.Fixed3D
        Me.Label9.Font = New System.Drawing.Font("Calibri", 30.0!)
        Me.Label9.Location = New System.Drawing.Point(229, 151)
        Me.Label9.Name = "Label9"
        Me.Label9.Size = New System.Drawing.Size(45, 45)
        Me.Label9.TabIndex = 39
        '
        'Button20
        '
        Me.Button20.BackColor = System.Drawing.Color.Transparent
        Me.Button20.BackgroundImage = CType(resources.GetObject("Button20.BackgroundImage"), System.Drawing.Image)
        Me.Button20.Cursor = System.Windows.Forms.Cursors.Hand
        Me.Button20.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.Button20.Font = New System.Drawing.Font("Calibri", 9.0!, System.Drawing.FontStyle.Bold, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Button20.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
        Me.Button20.Location = New System.Drawing.Point(365, 0)
        Me.Button20.Name = "Button20"
        Me.Button20.Size = New System.Drawing.Size(27, 23)
        Me.Button20.TabIndex = 41
        Me.Button20.Text = "X"
        Me.Button20.UseVisualStyleBackColor = False
        '
        'Label10
        '
        Me.Label10.AutoSize = True
        Me.Label10.BackColor = System.Drawing.Color.Transparent
        Me.Label10.Font = New System.Drawing.Font("Calibri", 10.25!)
        Me.Label10.ForeColor = System.Drawing.Color.Transparent
        Me.Label10.Location = New System.Drawing.Point(16, 89)
        Me.Label10.Name = "Label10"
        Me.Label10.Size = New System.Drawing.Size(43, 17)
        Me.Label10.TabIndex = 42
        Me.Label10.Text = "Score:"
        '
        'Label11
        '
        Me.Label11.AutoSize = True
        Me.Label11.BackColor = System.Drawing.Color.Transparent
        Me.Label11.Font = New System.Drawing.Font("Calibri", 10.25!)
        Me.Label11.ForeColor = System.Drawing.Color.Transparent
        Me.Label11.Location = New System.Drawing.Point(65, 89)
        Me.Label11.Name = "Label11"
        Me.Label11.Size = New System.Drawing.Size(32, 17)
        Me.Label11.TabIndex = 43
        Me.Label11.Text = "0 - 0"
        '
        'Button21
        '
        Me.Button21.BackColor = System.Drawing.Color.Transparent
        Me.Button21.BackgroundImage = Global.TicTacToe.My.Resources.Resources.langbar_big_rød
        Me.Button21.Cursor = System.Windows.Forms.Cursors.Hand
        Me.Button21.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.Button21.Font = New System.Drawing.Font("Calibri", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Button21.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
        Me.Button21.Location = New System.Drawing.Point(279, 227)
        Me.Button21.Name = "Button21"
        Me.Button21.Size = New System.Drawing.Size(99, 23)
        Me.Button21.TabIndex = 44
        Me.Button21.Text = "Nytt Spill"
        Me.Button21.UseVisualStyleBackColor = False
        '
        'Label12
        '
        Me.Label12.AutoSize = True
        Me.Label12.BackColor = System.Drawing.Color.Transparent
        Me.Label12.Font = New System.Drawing.Font("Calibri", 10.25!)
        Me.Label12.ForeColor = System.Drawing.SystemColors.ActiveCaptionText
        Me.Label12.Location = New System.Drawing.Point(294, 89)
        Me.Label12.Name = "Label12"
        Me.Label12.Size = New System.Drawing.Size(46, 17)
        Me.Label12.TabIndex = 45
        Me.Label12.Text = "Spiller:"
        '
        'Label13
        '
        Me.Label13.AutoSize = True
        Me.Label13.BackColor = System.Drawing.Color.Transparent
        Me.Label13.Font = New System.Drawing.Font("Calibri", 28.25!)
        Me.Label13.ForeColor = System.Drawing.Color.White
        Me.Label13.Location = New System.Drawing.Point(339, 66)
        Me.Label13.Name = "Label13"
        Me.Label13.Size = New System.Drawing.Size(39, 46)
        Me.Label13.TabIndex = 46
        Me.Label13.Text = "1"
        '
        'Button1
        '
        Me.Button1.BackColor = System.Drawing.Color.Transparent
        Me.Button1.BackgroundImage = Global.TicTacToe.My.Resources.Resources.langbar_big_yellow
        Me.Button1.Cursor = System.Windows.Forms.Cursors.Hand
        Me.Button1.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.Button1.Font = New System.Drawing.Font("Calibri", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Button1.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Button1.Location = New System.Drawing.Point(178, 227)
        Me.Button1.Name = "Button1"
        Me.Button1.Size = New System.Drawing.Size(95, 23)
        Me.Button1.TabIndex = 64
        Me.Button1.Text = "Meny"
        Me.Button1.UseVisualStyleBackColor = False
        '
        'Button19
        '
        Me.Button19.BackColor = System.Drawing.Color.Transparent
        Me.Button19.BackgroundImage = Global.TicTacToe.My.Resources.Resources.langbar_big
        Me.Button19.Cursor = System.Windows.Forms.Cursors.Hand
        Me.Button19.FlatStyle = System.Windows.Forms.FlatStyle.Flat
        Me.Button19.Font = New System.Drawing.Font("Calibri", 9.0!, System.Drawing.FontStyle.Regular, System.Drawing.GraphicsUnit.Point, CType(0, Byte))
        Me.Button19.ForeColor = System.Drawing.SystemColors.ControlText
        Me.Button19.Location = New System.Drawing.Point(12, 227)
        Me.Button19.Name = "Button19"
        Me.Button19.Size = New System.Drawing.Size(160, 23)
        Me.Button19.TabIndex = 63
        Me.Button19.Text = "Ny Runde"
        Me.Button19.UseVisualStyleBackColor = False
        '
        'Form1
        '
        Me.AutoScaleDimensions = New System.Drawing.SizeF(6.0!, 13.0!)
        Me.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font
        Me.BackgroundImage = Global.TicTacToe.My.Resources.Resources._890579818_6901fc666c_b
        Me.ClientSize = New System.Drawing.Size(390, 260)
        Me.Controls.Add(Me.Button1)
        Me.Controls.Add(Me.Button19)
        Me.Controls.Add(Me.Label13)
        Me.Controls.Add(Me.Label12)
        Me.Controls.Add(Me.Button21)
        Me.Controls.Add(Me.Label11)
        Me.Controls.Add(Me.Label10)
        Me.Controls.Add(Me.Button20)
        Me.Controls.Add(Me.Label9)
        Me.Controls.Add(Me.Label8)
        Me.Controls.Add(Me.Label7)
        Me.Controls.Add(Me.Label6)
        Me.Controls.Add(Me.Label5)
        Me.Controls.Add(Me.Label4)
        Me.Controls.Add(Me.Label3)
        Me.Controls.Add(Me.Label2)
        Me.Controls.Add(Me.Label1)
        Me.Controls.Add(Me.Header)
        Me.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None
        Me.Icon = CType(resources.GetObject("$this.Icon"), System.Drawing.Icon)
        Me.MaximizeBox = False
        Me.Name = "Form1"
        Me.StartPosition = System.Windows.Forms.FormStartPosition.CenterScreen
        Me.Text = "TicTacToe"
        Me.ResumeLayout(False)
        Me.PerformLayout()

    End Sub
    Friend WithEvents Header As System.Windows.Forms.Label
    Friend WithEvents Label1 As System.Windows.Forms.Label
    Friend WithEvents Label2 As System.Windows.Forms.Label
    Friend WithEvents Label3 As System.Windows.Forms.Label
    Friend WithEvents Label4 As System.Windows.Forms.Label
    Friend WithEvents Label5 As System.Windows.Forms.Label
    Friend WithEvents Label6 As System.Windows.Forms.Label
    Friend WithEvents Label7 As System.Windows.Forms.Label
    Friend WithEvents Label8 As System.Windows.Forms.Label
    Friend WithEvents Label9 As System.Windows.Forms.Label
    Friend WithEvents Button20 As System.Windows.Forms.Button
    Friend WithEvents Label10 As System.Windows.Forms.Label
    Friend WithEvents Label11 As System.Windows.Forms.Label
    Friend WithEvents Button21 As System.Windows.Forms.Button
    Friend WithEvents Label12 As System.Windows.Forms.Label
    Friend WithEvents Label13 As System.Windows.Forms.Label
    Friend WithEvents Button1 As System.Windows.Forms.Button
    Friend WithEvents Button19 As System.Windows.Forms.Button

End Class


text:
"""

  model tests
  ~~~~~~~~~~~

  tests canteen's data modelling layer.

  :author: Sam Gammon <sg@samgammon.com>
  :copyright: (c) Sam Gammon, 2014
  :license: This software makes use of the MIT Open Source License.
            A copy of this license is included as ``LICENSE.md`` in
            the root of the project.

"""

if __debug__:

  # stdlib
  import os

  # canteen tests
  from canteen.test import FrameworkTest

  ## ModelExportTests
  class ModelExportTests(FrameworkTest):

    """ Tests objects exported by `model`. """

    def test_concrete(self):

      """ Test that we can import concrete classes. """

      try:
        from canteen import model
        from canteen.model import Key
        from canteen.model import Model
        from canteen.model import Property
        from canteen.model import AbstractKey
        from canteen.model import AbstractModel

      except ImportError:  # pragma: no cover
        return self.fail("Failed to import concrete classes exported by Model.")

      else:
        self.assertTrue(Key)  # must export Key
        self.assertTrue(Model)  # must export Model
        self.assertTrue(Property)  # must export Property
        self.assertTrue(AbstractKey)  # must export AbstractKey
        self.assertTrue(AbstractModel)  # must export AbstractModel
        self.assertIsInstance(model, type(os))  # must be a module (lol)

  __all__ = (
      'test_graph',
      'test_key',
      'test_meta',
      'test_model',
      'test_query')


text:
Importing APEX Code Style in Eclipse
====================================
For Eclipse there are 2 configuration files
1. .settings/apex-style.xml : this contains Java formatter settings.
2. .settings/apex-importorder.importorder : this specifies the accepted import order for Apex projects.

##To import Apex format style
1. On the main menu, choose Eclipse | Preferences.
2. Go to Java | Code Style | Formatter and click on 'Import'.
3. In the Import Profile dialog box that opens select the `.settings/apex-style.xml`.
4. Apply the changes.

##To import Apex import order
1. On the main menu, choose Eclipse | Preferences.
2. Go to Java | Code Style | Organize Imports and click on 'Import'.
3. In the Load Import Order from File dialog box that opens select `.settings/apex-importorder.importorder`.
4. Apply the changes.

##Trailing whitespace
Apex checkstyle enforces no trailing whitespace. You can have Eclipse automatically remove trailing whitespace:
http://stackoverflow.com/questions/1043433/how-to-auto-remove-trailing-whitespace-in-eclipse/2618521#2618521


text:
package fzf

import (
	"os"
	"os/signal"
	"syscall"
)

func notifyOnResize(resizeChan chan<- os.Signal) {
	signal.Notify(resizeChan, syscall.SIGWINCH)
}

func notifyStop(p *os.Process) {
	p.Signal(syscall.SIGSTOP)
}

func notifyOnCont(resizeChan chan<- os.Signal) {
	signal.Notify(resizeChan, syscall.SIGCONT)
}


text:
'''
Created by auto_sdk on 2015.04.21
'''
from aliyun.api.base import RestApi
class Ecs20130110CreateSnapshotRequest(RestApi):
	def __init__(self,domain='ecs.aliyuncs.com',port=80):
		RestApi.__init__(self,domain, port)
		self.ClientToken = None
		self.DiskId = None
		self.InstanceId = None
		self.SnapshotName = None

	def getapiname(self):
		return 'ecs.aliyuncs.com.CreateSnapshot.2013-01-10'


text:
In order for you to be able to run docker inside the container, you must run in privileged mode.
This is built off of jpetazzo/dind image.

```
docker run --privileged rancher/docker-dind-base
```

If a Command is passed in on startup, then run the following:

```
/usr/local/bin/wrapdocker
```

before trying to start any containers within docker.

# License
Copyright (c) 2014-2015 [Rancher Labs, Inc.](http://rancher.com)

Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at

[http://www.apache.org/licenses/LICENSE-2.0](http://www.apache.org/licenses/LICENSE-2.0)

Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.


text:
module Azure::Web::Mgmt::V2018_02_01
  module Models
    #
    # Value of resource metric.
    #
    class ResourceMetricValue

      include MsRestAzure

      # @return [String] Value timestamp.
      attr_accessor :timestamp

      # @return [Float] Value average.
      attr_accessor :average

      # @return [Float] Value minimum.
      attr_accessor :minimum

      # @return [Float] Value maximum.
      attr_accessor :maximum

      # @return [Float] Value total.
      attr_accessor :total

      # @return [Float] Value count.
      attr_accessor :count

      # @return [Array<ResourceMetricProperty>] Resource metric properties
      # collection.
      attr_accessor :properties

      #
      # Mapper for ResourceMetricValue class as Ruby Hash.
      # This will be used for serialization/deserialization.
      #
      def self.mapper()
        {
          client_side_validation: true,
          required: false,
          serialized_name: 'ResourceMetricValue',
          type: {
            name: 'Composite',
            class_name: 'ResourceMetricValue',
            model_properties: {
              timestamp: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'timestamp',
                type: {
                  name: 'String'
                }
              },
              average: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'average',
                type: {
                  name: 'Double'
                }
              },
              minimum: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'minimum',
                type: {
                  name: 'Double'
                }
              },
              maximum: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'maximum',
                type: {
                  name: 'Double'
                }
              },
              total: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'total',
                type: {
                  name: 'Double'
                }
              },
              count: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'count',
                type: {
                  name: 'Double'
                }
              },
              properties: {
                client_side_validation: true,
                required: false,
                read_only: true,
                serialized_name: 'properties',
                type: {
                  name: 'Sequence',
                  element: {
                      client_side_validation: true,
                      required: false,
                      serialized_name: 'ResourceMetricPropertyElementType',
                      type: {
                        name: 'Composite',
                        class_name: 'ResourceMetricProperty'
                      }
                  }
                }
              }
            }
          }
        }
      end
    end
  end
end


text:
define(['jquery', 'ekyna-modal', 'ekyna-dispatcher', 'ekyna-ui', 'jquery/form', 'bootstrap'], function($, Modal, Dispatcher) {
    "use strict";

    function initView() {
        $('.sale-view [data-toggle="popover"]').popover({
            trigger: 'hover',
            placement: 'top',
            html: true
        });

        // TODO Toggle recalculate disabled on quantity change
    }

    function parseResponse(response, $saleView) {
        var $xml = $(response),
            $view = $xml.find('view');

        if (1 === $view.size()) {
            $saleView.replaceWith($($view.text()));

            Dispatcher.trigger('ekyna_commerce.sale_view_response', response);

            initView();

            return true;
        }

        return false;
    }

    $(document).on('click', '.sale-view [data-sale-modal]', function(e) {
        e.preventDefault();

        var $this = $(this),
            $saleView = $this.closest('.sale-view');

        var modal = new Modal();
        modal.load({url: $this.attr('href')});

        $(modal).on('ekyna.modal.response', function (modalEvent) {
            if (modalEvent.contentType === 'xml') {
                if (parseResponse(modalEvent.content, $saleView)) {
                    modalEvent.preventDefault();
                    modalEvent.modal.close();
                }
            }
        });

        return false;
    });

    $(document).on('click', '.sale-view [data-sale-xhr]', function(e) {
        e.preventDefault();

        var $this = $(this), confirmation = $this.data('confirm');
        if (confirmation && confirmation.length && !confirm(confirmation)) {
            return false;
        }

        var $saleView = $this.closest('.sale-view'),
            method = $this.data('sale-xhr');

        $saleView.loadingSpinner();

        var xhr = $.ajax({
            url: $(this).attr('href'),
            method: method || 'post',
            dataType: 'xml'
        });
        xhr.done(function(response) {
            parseResponse(response, $saleView);
        });

        return false;
    });

    $(document).on('click', '.sale-view [data-sale-toggle-all-children]', function(e) {
        e.stopPropagation();
        e.preventDefault();

        var $link = $(e.currentTarget),
            $saleView = $link.closest('.sale-view'),
            $children = $saleView.find('tr[data-parent]'),
            hidden = $children.filter(':not(:visible)').length,
            visible = $children.filter(':visible').length;

        if (hidden > visible) {
            $children.show();
        } else {
            $children.hide();
        }

        return false;
    });

    $(document).on('click', '.sale-view [data-sale-toggle-children]', function(e) {
        e.stopPropagation();
        e.preventDefault();

        var $link = $(e.currentTarget),
            $saleView = $link.closest('.sale-view'),
            id = $link.data('sale-toggle-children'),
            shown = !!$link.data('sale-toggle-shown');

        function hideChildren($children) {
            $children.each(function() {
                $(this).hide().find('[data-sale-toggle-children]').each(function() {
                    var $link = $(this),
                        id = $link.data('sale-toggle-children'),
                        shown = !!$link.data('sale-toggle-shown');

                    if (id && shown) {
                        hideChildren($saleView.find('tr[data-parent="' + id + '"]'));
                        $link.data('sale-toggle-shown', false)
                    }
                });
            })
        }

        if (id) {
            var $children = $saleView.find('tr[data-parent="' + id + '"]');
            if (shown) {
                hideChildren($children);
            } else {
                $children.show();
            }
            $link.data('sale-toggle-shown', !shown);
        }

        return false;
    });

    $(document).on('submit', '.sale-view form', function(e) {
        e.preventDefault();

        var $saleView = $(e.target).closest('.sale-view').loadingSpinner();

        $(e.target).closest('form').ajaxSubmit({
            dataType: 'xml',
            success: function(response) {
                parseResponse(response, $saleView);
            }
        });

        return false;
    });

    initView();
});


text:
<?php
namespace ZeroReactExamples\Utilits;

class Timestamp {
	public function getTime() {
		$now = \DateTime::createFromFormat('U.u', microtime(true));
		return $now->format("H:i:s.u");
	}
}


text:
function y=rdct(x,n,a,b)
%RDCT     Discrete cosine transform of real data Y=(X,N,A,B)
% Data is truncated/padded to length N.
%
% This routine is equivalent to multiplying by the matrix
%
%   rdct(eye(n)) = diag([sqrt(2)*B/A repmat(2/A,1,n-1)]) * cos((0:n-1)'*(0.5:n)*pi/n)
%
% Default values of the scaling factors are A=sqrt(2N) and B=1 which
% results in an orthogonal matrix. Other common values are A=1 or N and/or B=1 or sqrt(2).
% If b~=1 then the columns are no longer orthogonal.
%
% see IRDCT for the inverse transform

% BUG: in line 51 we should do chopping after transform and not before

%      Copyright (C) Mike Brookes 1998
%      Version: $Id: rdct.m,v 1.6 2007/05/04 07:01:39 dmb Exp $
%
%   VOICEBOX is a MATLAB toolbox for speech processing.
%   Home page: http://www.ee.ic.ac.uk/hp/staff/dmb/voicebox/voicebox.html
%
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%
%   This program is free software; you can redistribute it and/or modify
%   it under the terms of the GNU General Public License as published by
%   the Free Software Foundation; either version 2 of the License, or
%   (at your option) any later version.
%
%   This program is distributed in the hope that it will be useful,
%   but WITHOUT ANY WARRANTY; without even the implied warranty of
%   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
%   GNU General Public License for more details.
%
%   You can obtain a copy of the GNU General Public License from
%   http://www.gnu.org/copyleft/gpl.html or by writing to
%   Free Software Foundation, Inc.,675 Mass Ave, Cambridge, MA 02139, USA.
%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%%

fl=size(x,1)==1;
if fl x=x(:); end
[m,k]=size(x);
if nargin<2 n=m;
end
if nargin<4 b=1;
    if nargin<3 a=sqrt(2*n);
    end
    end
if n>m x=[x; zeros(n-m,k)];
elseif n<m x(n+1:m,:)=[];
end

x=[x(1:2:n,:); x(2*fix(n/2):-2:2,:)];
z=[sqrt(2) 2*exp((-0.5i*pi/n)*(1:n-1))].';
y=real(fft(x).*z(:,ones(1,k)))/a;
y(1,:)=y(1,:)*b;
if fl y=y.'; end


text:
package it.gmariotti.cardslib.library.prototypes;

/**
 * Default card section
 *
 * @author Gabriele Mariotti (gabri.mariotti@gmail.com)
 */
public class CardSection {

    int firstPosition;
    int sectionedPosition;
    CharSequence title;

    // -------------------------------------------------------------
    // Constructor
    // -------------------------------------------------------------

    public CardSection(int firstPosition, CharSequence title) {
        this.firstPosition = firstPosition;
        this.title = title;
    }

    /**
     * @return the title
     */
    public CharSequence getTitle() {
        return title;
    }
}


text:
import unittest

from telemetry.internal import story_runner
from telemetry.page import page
from telemetry.page import legacy_page_test
from telemetry.page import shared_page_state
from telemetry import story as story_module
from telemetry.testing import fakes
from telemetry.util import wpr_modes

def SetUpPageRunnerArguments(options):
  parser = options.CreateParser()
  story_runner.AddCommandLineArgs(parser)
  options.MergeDefaultValues(parser.get_default_values())
  story_runner.ProcessCommandLineArgs(parser, options)

class DummyTest(legacy_page_test.LegacyPageTest):

  def ValidateAndMeasurePage(self, *_):
    pass

class SharedPageStateTests(unittest.TestCase):

  def setUp(self):
    self.options = fakes.CreateBrowserFinderOptions()
    self.options.use_live_sites = False
    self.options.output_formats = ['none']
    self.options.suppress_gtest_report = True

  def testUseLiveSitesFlagSet(self):
    self.options.use_live_sites = True
    run_state = shared_page_state.SharedPageState(
        DummyTest(), self.options, story_module.StorySet())
    self.assertTrue(run_state.platform.network_controller.is_open)
    self.assertEquals(run_state.platform.network_controller.wpr_mode,
                      wpr_modes.WPR_OFF)
    self.assertTrue(run_state.platform.network_controller.use_live_traffic)

  def testUseLiveSitesFlagUnset(self):
    run_state = shared_page_state.SharedPageState(
        DummyTest(), self.options, story_module.StorySet())
    self.assertTrue(run_state.platform.network_controller.is_open)
    self.assertEquals(run_state.platform.network_controller.wpr_mode,
                      wpr_modes.WPR_REPLAY)
    self.assertFalse(run_state.platform.network_controller.use_live_traffic)

  def testWPRRecordEnable(self):
    self.options.browser_options.wpr_mode = wpr_modes.WPR_RECORD
    run_state = shared_page_state.SharedPageState(
        DummyTest(), self.options, story_module.StorySet())
    self.assertTrue(run_state.platform.network_controller.is_open)
    self.assertEquals(run_state.platform.network_controller.wpr_mode,
                      wpr_modes.WPR_RECORD)
    self.assertFalse(run_state.platform.network_controller.use_live_traffic)

  def testConstructorCallsSetOptions(self):
    test = DummyTest()
    shared_page_state.SharedPageState(
        test, self.options, story_module.StorySet())
    self.assertEqual(test.options, self.options)

  def assertUserAgentSetCorrectly(
      self, shared_page_state_class, expected_user_agent):
    story = page.Page(
        'http://www.google.com',
        shared_page_state_class=shared_page_state_class)
    test = DummyTest()
    story_set = story_module.StorySet()
    story_set.AddStory(story)
    story.shared_state_class(test, self.options, story_set)
    browser_options = self.options.browser_options
    actual_user_agent = browser_options.browser_user_agent_type
    self.assertEqual(expected_user_agent, actual_user_agent)

  def testPageStatesUserAgentType(self):
    self.assertUserAgentSetCorrectly(
        shared_page_state.SharedMobilePageState, 'mobile')
    self.assertUserAgentSetCorrectly(
        shared_page_state.SharedDesktopPageState, 'desktop')
    self.assertUserAgentSetCorrectly(
        shared_page_state.SharedTabletPageState, 'tablet')
    self.assertUserAgentSetCorrectly(
        shared_page_state.Shared10InchTabletPageState, 'tablet_10_inch')
    self.assertUserAgentSetCorrectly(
        shared_page_state.SharedPageState, None)

  def testBrowserStartupURLSetCorrectly(self):
    story_set = story_module.StorySet()
    google_page = page.Page(
        'http://www.google.com',
        startup_url='http://www.google.com', page_set=story_set)
    example_page = page.Page(
        'https://www.example.com',
        startup_url='https://www.example.com', page_set=story_set)
    gmail_page = page.Page(
        'https://www.gmail.com',
        startup_url='https://www.gmail.com', page_set=story_set)

    for p in (google_page, example_page, gmail_page):
      story_set.AddStory(p)

    shared_state = shared_page_state.SharedPageState(
        DummyTest(), self.options, story_set)

    for p in (google_page, example_page, gmail_page):
      shared_state.WillRunStory(p)
      self.assertEquals(
          p.startup_url, self.options.browser_options.startup_url)


text:
'use strict';

const Platform = require('Platform');
const PropTypes = require('ReactPropTypes');
const React = require('React');
const StyleSheet = require('StyleSheet');
const View = require('View');
const deprecatedPropType = require('deprecatedPropType');

const requireNativeComponent = require('requireNativeComponent');
const RCTModalHostView = requireNativeComponent('RCTModalHostView', null);

/**
 * A Modal component covers the native view (e.g. UIViewController, Activity)
 * that contains the React Native root.
 *
 * Use Modal in hybrid apps that embed React Native; Modal allows the portion of
 * your app written in React Native to present content above the enclosing
 * native view hierarchy.
 *
 * In apps written with React Native from the root view down, you should use
 * Navigator instead of Modal. With a top-level Navigator, you have more control
 * over how to present the modal scene over the rest of your app by using the
 * configureScene property.
 */
class Modal extends React.Component {
  static propTypes = {
    animated: deprecatedPropType(
      PropTypes.bool,
      'Use the `animationType` prop instead.'
    ),
    animationType: PropTypes.oneOf(['none', 'slide', 'fade']),
    transparent: PropTypes.bool,
    visible: PropTypes.bool,
    onRequestClose: Platform.OS === 'android' ? PropTypes.func.isRequired : PropTypes.func,
    onShow: PropTypes.func,
  };

  static defaultProps = {
    visible: true,
  };

  render(): ?ReactElement {
    if (this.props.visible === false) {
      return null;
    }

    const containerBackgroundColor = {
      backgroundColor: this.props.transparent ? 'transparent' : 'white',
    };

    let animationType = this.props.animationType;
    if (!animationType) {
      // manually setting default prop here to keep support for the deprecated 'animated' prop
      animationType = 'none';
      if (this.props.animated) {
        animationType = 'slide';
      }
    }

    return (
      <RCTModalHostView
        animationType={animationType}
        transparent={this.props.transparent}
        onRequestClose={this.props.onRequestClose}
        onShow={this.props.onShow}
        style={styles.modal}
        onStartShouldSetResponder={this._shouldSetResponder}
        >
        <View style={[styles.container, containerBackgroundColor]}>
          {this.props.children}
        </View>
      </RCTModalHostView>
    );
  }

  // We don't want any responder events bubbling out of the modal.
  _shouldSetResponder(): boolean {
    return true;
  }
}

const styles = StyleSheet.create({
  modal: {
    position: 'absolute',
  },
  container: {
    position: 'absolute',
    left: 0,
    top: 0,
  }
});

module.exports = Modal;


text:
/* This program is designed to Compute and display the Volume
and Surface Area of a box with Height 10cm, Lentgh 11.5cm and Width 2.5cm.
Author: Robert Eviston
Date: 30th September 2013 */

#include <stdio.h>

main()
{
    int height;
    float length;
    float width;

    height = 10;
    length = 11.5;
    width = 2.5;

    printf("The volume of the box is %fcm\n\n", height * length * width);
    printf("The surface area of a box is %fcm", ((length * height) *2) + ((length * width) *2) + ((height * width) *2));

    getchar();
}


text:
.preview img {
  max-width: 61.8%;
  margin-right : auto;
  margin-left: auto;
  display: table-cell;
}


text:
class TurkSiteCategories < ActiveRecord::Migration
  def self.up
    create_table :turk_site_categories do |t|
      t.column :name, :string
      t.column :description, :string
    end

    add_column :turk_sites, :turk_site_category_id, :integer
  end

  def self.down
    drop_table :turk_site_categories
    remove_column :turk_sites, :turk_site_category_id
  end
end