text:
<title>OGRE: Ogre::DynLibManager Class Reference - OGRE Documentation</title> <meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1">
<link type="text/css" rel="stylesheet" href="doxygen.css">
<link type="text/css" rel="stylesheet" href="tabs.css">

Main Page

Related Pages

Modules

Namespaces

Classes

Files

Directories

Class List

Class Index

Class Hierarchy

Class Members

Ogre

Ogre::DynLibManager

Public Member Functions |
Static Public Member Functions |
Protected Types |
Protected Attributes |
Static Protected Attributes

Ogre::DynLibManager Class Reference

[General]

Manager for Dynamic-loading Libraries.
More...

#include <OgreDynLibManager.h>

Inheritance diagram for Ogre::DynLibManager:

<map name="Ogre_1_1DynLibManager_inherit__map" id="Ogre_1_1DynLibManager_inherit__map">
<area shape="rect" id="node2" href="classOgre_1_1Singleton.html" title="Ogre::Singleton\< DynLibManager \>" alt="" coords="5,5,256,35"/><area shape="rect" id="node4" href="classOgre_1_1AllocatedObject.html" title="Superclass for all objects that wish to use custom memory allocators when their new / delete operator..." alt="" coords="280,5,373,35"/></map>
[legend]

List of all members.

Public Member Functions

 	DynLibManager ()

 	Default constructor.

virtual 	~DynLibManager ()

 	Default destructor.

DynLib * 	load (const String &filename)

 	Loads the passed library.

void 	unload (DynLib *lib)

 	Unloads the passed library.

void * 	operator new (size_t sz, const char *file, int line, const char *func)

 	operator new, with debug line info

void * 	operator new (size_t sz)

void * 	operator new (size_t sz, void *ptr)

 	placement operator new

void * 	operator new[] (size_t sz, const char *file, int line, const char *func)

 	array operator new, with debug line info

void * 	operator new[] (size_t sz)

void 	operator delete (void *ptr)

void 	operator delete (void *ptr, void *)

void 	operator delete (void *ptr, const char *, int, const char *)

void 	operator delete[] (void *ptr)

void 	operator delete[] (void *ptr, const char *, int, const char *)

Static Public Member Functions

static DynLibManager & 	getSingleton (void)

 	Override standard Singleton retrieval.

static DynLibManager * 	getSingletonPtr (void)

 	Override standard Singleton retrieval.

static DynLibManager & 	getSingleton (void)

static DynLibManager * 	getSingletonPtr (void)

Protected Types

typedef map< String, DynLib * >

::type 	DynLibList

Protected Attributes

DynLibList 	mLibList

Static Protected Attributes

static DynLibManager * 	ms_Singleton

Detailed Description

Manager for Dynamic-loading Libraries.

Remarks:

This manager keeps a track of all the open dynamic-loading libraries, opens them and returns references to already-open libraries.

Definition at line 47 of file OgreDynLibManager.h.

Member Typedef Documentation

          typedef map<String, DynLib*>::type Ogre::DynLibManager::DynLibList [protected]

Definition at line 50 of file OgreDynLibManager.h.

Constructor & Destructor Documentation

          Ogre::DynLibManager::DynLibManager
          (

           )

Default constructor.

Note:

Should never be called as the singleton is automatically created during the creation of the Root object.

See also:

Root::Root

          virtual Ogre::DynLibManager::~DynLibManager
          (

           )
           [virtual]

Default destructor.

See also:

Root::~Root

Member Function Documentation

          static DynLibManager& Ogre::DynLibManager::getSingleton
          (
          void

           )
           [static]

Override standard Singleton retrieval.

Remarks:

Why do we do this? Well, it's because the Singleton implementation is in a .h file, which means it gets compiled into anybody who includes it. This is needed for the Singleton template to work, but we actually only want it compiled into the implementation of the class based on the Singleton, not all of them. If we don't change this, we get link errors when trying to use the Singleton-based class from an outside dll.

This method just delegates to the template version anyway, but the implementation stays in this single compilation unit, preventing link errors.

          static DynLibManager & Ogre::Singleton< DynLibManager  >::getSingleton
          (
          void

           )
           [static, inherited]

Definition at line 90 of file OgreSingleton.h.

          static DynLibManager* Ogre::DynLibManager::getSingletonPtr
          (
          void

           )
           [static]

Override standard Singleton retrieval.

Remarks:

Why do we do this? Well, it's because the Singleton implementation is in a .h file, which means it gets compiled into anybody who includes it. This is needed for the Singleton template to work, but we actually only want it compiled into the implementation of the class based on the Singleton, not all of them. If we don't change this, we get link errors when trying to use the Singleton-based class from an outside dll.

This method just delegates to the template version anyway, but the implementation stays in this single compilation unit, preventing link errors.

          static DynLibManager * Ogre::Singleton< DynLibManager  >::getSingletonPtr
          (
          void

           )
           [static, inherited]

Definition at line 92 of file OgreSingleton.h.

          DynLib* Ogre::DynLibManager::load
          (
          const String &
           filename
           )

Loads the passed library.

Parameters:

	filename 	The name of the library. The extension can be omitted

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete
          (
          void *
           ptr,

          void *

          )
          		 [inherited]

Definition at line 101 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete
          (
          void *
           ptr
           )
           [inherited]

Definition at line 95 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete
          (
          void *
           ptr,

          const char *
          ,

          int
          ,

          const char *

          )
          		 [inherited]

Definition at line 107 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete[]
          (
          void *
           ptr
           )
           [inherited]

Definition at line 112 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void Ogre::AllocatedObject< Alloc >::operator delete[]
          (
          void *
           ptr,

          const char *
          ,

          int
          ,

          const char *

          )
          		 [inherited]

Definition at line 118 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new
          (
          size_t
           sz
           )
           [inherited]

Definition at line 72 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new
          (
          size_t
           sz,

          void *
           ptr

          )
          		 [inherited]

placement operator new

Definition at line 78 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new
          (
          size_t
           sz,

          const char *
           file,

          int
           line,

          const char *
           func

          )
          		 [inherited]

operator new, with debug line info

Definition at line 67 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new[]
          (
          size_t
           sz
           )
           [inherited]

Definition at line 90 of file OgreMemoryAllocatedObject.h.

template<class Alloc >

          void* Ogre::AllocatedObject< Alloc >::operator new[]
          (
          size_t
           sz,

          const char *
           file,

          int
           line,

          const char *
           func

          )
          		 [inherited]

array operator new, with debug line info

Definition at line 85 of file OgreMemoryAllocatedObject.h.

          void Ogre::DynLibManager::unload
          (
          DynLib *
           lib
           )

Unloads the passed library.

Parameters:

	filename 	The name of the library. The extension can be omitted

Member Data Documentation

          DynLibList Ogre::DynLibManager::mLibList [protected]

Definition at line 51 of file OgreDynLibManager.h.

          DynLibManager * Ogre::Singleton< DynLibManager  >::ms_Singleton [static, protected, inherited]

Definition at line 75 of file OgreSingleton.h.

The documentation for this class was generated from the following file:

OgreDynLibManager.h

Copyright © 2008 Torus Knot Software Ltd

This work is licensed under a Creative Commons Attribution-ShareAlike 3.0 Unported License.

Last modified Wed Nov 3 2010 19:24:54


text:
var math = require('mathjs'),
    precision  = require( './precision' );
/**
 * Checks if two numbers can (not must) be rounded numbers of an common number.
 * The minimum precision and number of digits can be adjusted.
 * The numbers have to met only one of both criteria.
 *
 * @param {number}  first number
 * @param {number}  second number
 * @param {number}  minimum precision (default = 2)
 * @param {number}  minimum number of digits (default = 8)
 */
module.exports = roundEqual = function ( x, y, precisionMin, digitsMin) {

  // use bignumbers from mathjs
  x = math.bignumber(x);
  y = math.bignumber(y);

  //set precisionMin
  precisionMin = math.bignumber(precisionMin || 2);
  digitsMin = math.bignumber(digitsMin || 6);
  // calculate precision of the leading digits
  var leadingDigitPrecisionX = math.chain(x).abs().log10().round().multiply(-1).done();
  var leadingDigitPrecisionY = math.chain(y).abs().log10().round().multiply(-1).done();
  // get max precision of leading digits (= leading digit precision of the smaller number)
  var leadingDigitPrecisionMax = math.max(leadingDigitPrecisionX,leadingDigitPrecisionY);
  // calculate min precision using min number of digits
  var digitsMinPrecision = math.chain(leadingDigitPrecisionMax).add(digitsMin).done();
  // use the lower min precisions (= "smaller obstacle" / only one criteria has to be met)
  precisionMin = math.min(precisionMin,digitsMinPrecision);

  // get precision
  var precisionX = math.max(precision(x),precisionMin);
  var precisionY = math.max(precision(y),precisionMin);
  var precisionMax = math.max(precisionX,precisionY);

  // calculate bounds
  /*
   * bound: the smallest number greater and the greatest number
   * smaller as all possible original values without assuming a
   * specific rounding method
   */
  var bigTen = math.bignumber(10);
  var lowerBoundX = math.subtract(x, math.pow(bigTen, -precisionX));
  var upperBoundX = math.add(x, math.pow(bigTen, -precisionX));
  var lowerBoundY = math.subtract(y, math.pow(bigTen, -precisionY));
  var upperBoundY = math.add(y, math.pow(bigTen, -precisionY));

  // check if ranges of original values are not distinct
  return ( math.equal(x, y)
        || lowerBoundX <= lowerBoundY && lowerBoundY <  upperBoundX // lower bound of y in range of x
        || lowerBoundX <  upperBoundY && upperBoundY <= upperBoundX // upper bound of y in range of x
        || lowerBoundY <= lowerBoundX && lowerBoundX <  upperBoundY // lower bound of x in range of y
        || lowerBoundY <  upperBoundX && upperBoundX <= upperBoundY // upper bound of x in range of y
        );
}

redpajama_set_name: RedPajamaGithub


text:
import math

import numpy as np
import scipy.integrate

class NumericalIntegrator(object):
    min_count = 2
    method = None

    def __call__(self, Y, dx):
        return self.method(Y, dx=dx)

class TrapezoidIntegrator(NumericalIntegrator):
    method = staticmethod(scipy.integrate.trapz)

class SimpsonIntegrator(NumericalIntegrator):
    method = staticmethod(scipy.integrate.simps)

class RombergIntegrator(NumericalIntegrator):
    min_count = 3
    method = staticmethod(scipy.integrate.romb)

class DomainIntegrator(object):

    def __init__(self, int_type):
        self.num_integrator = int_type()

    def integrate(self, X, Y):
        assert X.ndim == Y.ndim == 1
        assert X.shape == Y.shape
        assert len(X) >= self.num_integrator.min_count

        divs_f = math.log(len(X) - 1, 2.0)
        divs = int(divs_f)
        assert divs == divs_f

        dx = (X[-1] - X[0]) / (len(X) - 1)
        I = self.num_integrator(Y, dx)
        return I

    def integrate_base(self, active_medium, input_beam, Rho, Phi, fluence):
        assert Rho.ndim == Phi.ndim == 1
        assert fluence.shape == (Rho.shape + Phi.shape)

        integrate = lambda Y, X, xmax: self.integrate(X, Y) if len(X) > 1 else xmax * Y[0]

        radius = active_medium.radius
        if input_beam is not None:
            radius = min(radius, input_beam.rho_trunc)

        phi_integrals = np.apply_along_axis(integrate, 1, fluence, Phi, 2.0*math.pi)
        phi_integrals *= Rho if len(Rho) > 1 else radius/2.0
        rho_phi_integral = integrate(phi_integrals, Rho, radius)

        return rho_phi_integral


text:
module RailsBootstrapHelpers::Helpers::UrlHelper
  # Renders a Jasny Bootstrap action link. This method behaves just as "link_to"
  # but will render a Jasny Bootstrap action link instead of a regular link.
  # In addition to the options "link_to" handles, this method also handles the
  # following options:
  #
  # @option options [String, Symbol] :style the style of the link
  def action_link_to (*args, &block)
    RailsBootstrapHelpers::Renderers::ActionLinkRenderer.new(self, *args, &block).render
  end

  # Renders a Jasny Bootstrap row link. This method behaves just as "link_to"
  # but will render a Jasny Bootstrap row link instead of a regular link.
  def row_link_to (*args, &block)
    RailsBootstrapHelpers::Renderers::RowLinkRenderer.new(self, *args, &block).render
  end
end


text:
namespace Microsoft.Azure.Management.Monitor.Fluent
{
    using Microsoft.Azure.Management.Monitor.Fluent.Models;
    using Microsoft.Azure.Management.ResourceManager.Fluent.Core;
    using Microsoft.Rest.Azure;
    using System.Threading;
    using System.Threading.Tasks;

    /// <summary>
    /// Implementation for  ActivityLogAlerts.
    /// </summary>
    ///GENTHASH:Y29tLm1pY3Jvc29mdC5henVyZS5tYW5hZ2VtZW50Lm1vbml0b3IuaW1wbGVtZW50YXRpb24uQWN0aXZpdHlMb2dBbGVydHNJbXBs
    internal partial class ActivityLogAlertsImpl :
        TopLevelModifiableResources<IActivityLogAlert, ActivityLogAlertImpl, ActivityLogAlertResourceInner, IActivityLogAlertsOperations, MonitorManager>,
        IActivityLogAlerts
    {

        ///GENMHASH:F8D3B82AA31AB059BC1C918008DF3E2A:AFEB1F416BE811537ADFAB52035F7907
        internal ActivityLogAlertsImpl(MonitorManager monitorManager)
            : base(monitorManager.Inner.ActivityLogAlerts, monitorManager)
        {
        }

        ///GENMHASH:2FE8C4C2D5EAD7E37787838DE0B47D92:648BBDBC0D111882A7B3E1D836899F04
        protected override ActivityLogAlertImpl WrapModel(string name)
        {
            return new ActivityLogAlertImpl(name, new ActivityLogAlertResourceInner(), this.Manager);
        }

        ///GENMHASH:9F8B6BDE6F07CCC4CC4A20EA49624620:880FB60A0EB367E0C3B1159A89BC7B21
        protected override IActivityLogAlert WrapModel(ActivityLogAlertResourceInner inner)
        {
            if (inner == null)
            {
                return null;
            }

            return new ActivityLogAlertImpl(inner.Name, inner, this.Manager);
        }

        ///GENMHASH:8ACFB0E23F5F24AD384313679B65F404:AD7C28D26EC1F237B93E54AD31899691
        public ActivityLogAlertImpl Define(string name)
        {
            return WrapModel(name);
        }

        // catch up methods
        protected override async Task<IPage<ActivityLogAlertResourceInner>> ListInnerAsync(CancellationToken cancellationToken)
        {
            return new ActivityLogAlertResourceInnerPage(await Inner.ListBySubscriptionIdAsync(cancellationToken));
        }

        protected override async Task<IPage<ActivityLogAlertResourceInner>> ListInnerNextAsync(string link, CancellationToken cancellationToken)
        {
            return await Task.FromResult<IPage<ActivityLogAlertResourceInner>>(null);
        }

        protected override async Task<IPage<ActivityLogAlertResourceInner>> ListInnerByGroupAsync(string resourceGroupName, CancellationToken cancellationToken)
        {
            return new ActivityLogAlertResourceInnerPage(await Inner.ListByResourceGroupAsync(resourceGroupName, cancellationToken: cancellationToken));
        }

        protected override async Task<IPage<ActivityLogAlertResourceInner>> ListInnerByGroupNextAsync(string link, CancellationToken cancellationToken)
        {
            return await Task.FromResult<IPage<ActivityLogAlertResourceInner>>(null);
        }

        protected override async Task<ActivityLogAlertResourceInner> GetInnerByGroupAsync(string groupName, string name, CancellationToken cancellationToken)
        {
            return await Inner.GetAsync(groupName, name, cancellationToken);
        }

        protected override async Task DeleteInnerByGroupAsync(string groupName, string name, CancellationToken cancellationToken)
        {
            await Inner.DeleteAsync(groupName, name, cancellationToken: cancellationToken);
        }
    }
}


text:
ClientApp::ClientApp() {
}

void ClientApp::OnRegisterCustomSchemes(
    CefRefPtr<CefSchemeRegistrar> registrar) {
  // Default schemes that support cookies.
  cookieable_schemes_.push_back("http");
  cookieable_schemes_.push_back("https");

  RegisterCustomSchemes(registrar, cookieable_schemes_);
}

void ClientApp::OnContextInitialized() {

 CreateBrowserDelegates(browser_delegates_);

  // Register cookieable schemes with the global cookie manager.
  CefRefPtr<CefCookieManager> manager = CefCookieManager::GetGlobalManager();
  DCHECK(manager.get());
  manager->SetSupportedSchemes(cookieable_schemes_);

  print_handler_ = CreatePrintHandler();

  BrowserDelegateSet::iterator it = browser_delegates_.begin();
  for (; it != browser_delegates_.end(); ++it)
    (*it)->OnContextInitialized(this);
}

void ClientApp::OnBeforeChildProcessLaunch(
      CefRefPtr<CefCommandLine> command_line) {
  BrowserDelegateSet::iterator it = browser_delegates_.begin();
  for (; it != browser_delegates_.end(); ++it)
    (*it)->OnBeforeChildProcessLaunch(this, command_line);
}

void ClientApp::OnRenderProcessThreadCreated(
    CefRefPtr<CefListValue> extra_info) {
  BrowserDelegateSet::iterator it = browser_delegates_.begin();
  for (; it != browser_delegates_.end(); ++it)
    (*it)->OnRenderProcessThreadCreated(this, extra_info);
}

void ClientApp::OnRenderThreadCreated(CefRefPtr<CefListValue> extra_info) {
  CreateRenderDelegates(render_delegates_);

  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end(); ++it)
    (*it)->OnRenderThreadCreated(this, extra_info);
}

void ClientApp::OnWebKitInitialized() {
  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end(); ++it)
    (*it)->OnWebKitInitialized(this);
}

void ClientApp::OnBrowserCreated(CefRefPtr<CefBrowser> browser) {
  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end(); ++it)
    (*it)->OnBrowserCreated(this, browser);
}

void ClientApp::OnBrowserDestroyed(CefRefPtr<CefBrowser> browser) {
  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end(); ++it)
    (*it)->OnBrowserDestroyed(this, browser);
}

CefRefPtr<CefLoadHandler> ClientApp::GetLoadHandler() {
  CefRefPtr<CefLoadHandler> load_handler;
  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end() && !load_handler.get(); ++it)
    load_handler = (*it)->GetLoadHandler(this);

  return load_handler;
}

bool ClientApp::OnBeforeNavigation(CefRefPtr<CefBrowser> browser,
                                   CefRefPtr<CefFrame> frame,
                                   CefRefPtr<CefRequest> request,
                                   NavigationType navigation_type,
                                   bool is_redirect) {
  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end(); ++it) {
    if ((*it)->OnBeforeNavigation(this, browser, frame, request,
                                  navigation_type, is_redirect)) {
      return true;
    }
  }

  return false;
}

void ClientApp::OnContextCreated(CefRefPtr<CefBrowser> browser,
                                 CefRefPtr<CefFrame> frame,
                                 CefRefPtr<CefV8Context> context) {
  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end(); ++it)
    (*it)->OnContextCreated(this, browser, frame, context);
}

void ClientApp::OnContextReleased(CefRefPtr<CefBrowser> browser,
                                  CefRefPtr<CefFrame> frame,
                                  CefRefPtr<CefV8Context> context) {
  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end(); ++it)
    (*it)->OnContextReleased(this, browser, frame, context);
}

void ClientApp::OnUncaughtException(CefRefPtr<CefBrowser> browser,
                                    CefRefPtr<CefFrame> frame,
                                    CefRefPtr<CefV8Context> context,
                                    CefRefPtr<CefV8Exception> exception,
                                    CefRefPtr<CefV8StackTrace> stackTrace) {
  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end(); ++it) {
    (*it)->OnUncaughtException(this, browser, frame, context, exception,
                               stackTrace);
  }
}

void ClientApp::OnFocusedNodeChanged(CefRefPtr<CefBrowser> browser,
                                     CefRefPtr<CefFrame> frame,
                                     CefRefPtr<CefDOMNode> node) {
  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end(); ++it)
    (*it)->OnFocusedNodeChanged(this, browser, frame, node);
}

bool ClientApp::OnProcessMessageReceived(
    CefRefPtr<CefBrowser> browser,
    CefProcessId source_process,
    CefRefPtr<CefProcessMessage> message) {
  DCHECK_EQ(source_process, PID_BROWSER);

  bool handled = false;

  RenderDelegateSet::iterator it = render_delegates_.begin();
  for (; it != render_delegates_.end() && !handled; ++it) {
    handled = (*it)->OnProcessMessageReceived(this, browser, source_process,
                                              message);
  }

  return handled;
}


text:
using System;

namespace UnityTest.UnitTestRunner
{
	public interface ITestRunnerCallback
	{
		void TestStarted (string fullName);
		void TestFinished (ITestResult fullName);
		void RunStarted (string suiteName, int testCount);
		void RunFinished ();
		void RunFinishedException (Exception exception);
	}
}


text:
*Cauz I Can download my photos from VK with C++*

## Overview

In order to use my totally useless programm one should build it. It is crazy
thing and absolutely uselestt but now it easy to do with the following bash
commands

```bash
mkdir build
cd build
cmake ..
make -j4
```

After that it is needed to get access token which can be requested via oauth2
procedure. This util also provide web service to start authorization. So, run
the following in bash.

```bash
CIC_BASE_URL=/cauzican CIC_VERSION=5.69 ./cauzican serve
```

It is possible to specify VK API version, the default is `5.69`, or prefix to
web service root. Then open browser, type `http://<your-host:8080>/prefix/`,
submit form and allow your VK application to access to your personal
data(actually, photos). After all cauzican prints access token to terminal.

Now, when you have gotten access token you can download your photos to your
local host. There are two related variables needed to set. The first one is
access token surely and the second one is output dir which is the current dir
on default. So, run the following to fetch your photos.

```bash
CIC_TOKEN=token CIC_OUTDIR=some/dir ./cauzican fetch
```

As it was mentioned before there are some environment variables which defines
cauzican behavior. They are bellow.

- `CIC\_BASE\_URL` Base URL of your web server.
- `CIC\_PREFIX` Prefix URI of index page.
- `CIC\_OUTDIR` Output dir for downloaded photos.

- `CIC\_API\_KEY` VK API key of VK application.
- `CIC\_API\_SECRET` VK API secret key of VK application.
- `CIC\_REDIRECT` Redirect URI for OAuth2 protocol.
- `CIC\_TOKEN` Access token.
- `CIC\_VERSION` Version of VK API(`5.69` on default).


text:
import urllib2
import urllib
import re
import os

# structure : http://<ip>/<device>/<app>?t=<password>&p=<command>

class UrlCommands:
    pw = "SeniorProject"
    ip = "10.5.5.9"
    device = ""
    app = ""
    command = ""
    url = ""
    current = ""
    imageid = ""

    def __init__(self):
        self.command = ""

    # http://<ip>/camera/VR?t=<password>&p=%00
    def build_url(self, dev, a, com):
        self.url = "http://" + self.ip + "/" + dev + "/" + a + "?t=" + self.pw + "&p=" + "%" + com
        try:
            urllib2.urlopen(self.url)
            print self.url + " Command Sent.."
            print self.current                  # print the command and current stored debug info
            current = ""
        except urllib2.URLError:
            print "An error occurred while attempting to retrieve url: " + self.url

# BACPAC device commands: off, on, change_mode, start/stop capture
# http://<ip>/bacpac/PW?t=<password>&p=%01
    def turn_off(self):
        device = "bacpac"
        app = "PW"
        command = "00"
        current = "\tBACPAC:PW:00: Power down.."
        self.build_url(device, app, command)

    def turn_on(self):
        device = "bacpac"
        app = "PW"
        command = "01"
        current = "\tBACPAC:PW:01: Power On.."
        self.build_url(device, app, command)

    def change_mode(self):
        device = "bacpac"
        app = "PW"
        command = "02"
        current = "\tBACPAC:PW:02: Change Mode."
        self.build_url(device, app, command)

# http://<ip>/bacpac/SH?t=<password>&p=%01
    def start_capture(self):
        device = "bacpac"
        app = "SH"
        command = "01"
        current = "\tBACPAC:SH:01: * Start Capture"
        self.build_url(device, app, command)

    def stop_capture(self):
        device = "bacpac"
        app = "SH"
        command = "00"
        current = "\tBACPAC:SH:00: * Stop Capture"
        self.build_url(device, app, command)

# Camera preview methods on/off
# http://<ip>/camera/PV?t=<password>&p=%02
    def preview_on(self):
        device = "camera"
        app = "PV"
        command = "02"
        current = "\tCAMERA:PV:02: Preview On"
        self.build_url(device, app, command)

    def preview_off(self):
        device = "camera"
        app = "PV"
        command = "00"
        current = "\tCAMERA:PV:00: Preview Off"
        self.build_url(device, app, command)

# Camera mode methods
# http://<ip>/camera/CM?t=<password>&p=%00
    def enable_camera_mode(self):
        device = "camera"
        app = "CM"
        command = "00"
        self.build_url(device, app, command)

    def enable_photo_mode(self):
        device = "camera"
        app = "CM"
        command = "01"
        current = "\tCAMERA:CM:01: Photo Mode Enabled"
        self.build_url(device, app, command)

    def enable_burst_mode(self):
        device = "camera"
        app = "CM"
        command = "02"
        self.build_url(device, app, command)

    def enable_tl_mode(self):
        device = "camera"
        app = "CM"
        command = "03"
        self.build_url(device, app, command)

    def enable_tl2_mode(self):
        device = "camera"
        app = "CM"
        command = "04"
        self.build_url(device, app, command)

# Camera orientation methods
# http://<ip>/camera/UP?t=<password>&p=%00
    def set_head_up(self):
            device = "camera"
            app = "UP"
            command = "00"
            self.build_url(device, app, command)

    def set_head_down(self):
            device = "camera"
            app = "UP"
            command = "01"
            self.build_url(device, app, command)

# Video resolution methods
# http://<ip>/camera/VR?t=<password>&p=%00
    def set_video_resolution(self, r):

        if r == 'WVGA-60':
            command = "00"
        elif r == 'WVGA-120':
            command = "01"
        elif r == '720-30':
            command = "02"
        elif r == '720-60':
            command = "03"
        elif r == '960-30':
            command = "04"
        elif r == '960-60':
            command = "05"
        elif r == '1080-30':
            command = "06"
        else:
            print "Error occurred while setting camera's video resolution: " + r + " is not a valid parameter"
            command = "00"

        device = "camera"
        app = "VR"
        self.build_url(device, app, command)

    # methods to set photo resolutions
    # http://<ip>/camera/PR?t=<password>&p=%00
    def set_photo_resolution(self, r):
        if r == '11MP_WIDE':
            command = "00"
        elif r == '8MP_MEDIUM':
            command = "01"
        elif r == '5MP_WIDE':
            command = "02"
        elif r == '5MP_MEDIUM':
            command = "03"
        else:
            print "Error occurred while setting camera's photo resolution: " + r + " is not a valid parameter"
            command = "00"

        device = "camera"
        app = "PR"
        self.build_url(device, app, command)

    # Camera timer settings
    # http://<ip>/camera/TI?t=<password>&p=%00
    def set_timer(self, tm):
        if tm == 0.5:
            command = "00"
        elif tm == 1:
            command = "01"
        elif tm == 2:
            command = "02"
        elif tm == 5:
            command = "03"
        elif tm == 10:
            command = "04"
        elif tm == 30:
            command = "05"
        elif tm == 60:
            command = "06"
        else:
            print "Error occurred::<set_timer>::timer interval: " + tm + " is not a valid parameter"
            command = "00"

        device = "camera"
        app = "TI"
        self.build_url(device, app, command)

    # home_directory = "http://10.5.5.9:8080/videos/DCIM/100GOPRO/"
    def get_photo(self):
        home_dir = "http://" + self.ip + ":8080/videos/DCIM/100GOPRO/"  # Cherokee Web Server
        repeat = True

        # Waiting for the server to update
        while repeat == True:
            path = urllib2.urlopen(home_dir)                                # Get the Cherokee URL
            string = path.read()                                            # Get the HTML info from web server
            pattern = re.compile('\w\w\w\w\w\w\w\w.JPG"')                   # regular expression to find all JPG names
            files = pattern.findall(string)                                 # get the filenames into a list
            temp = files[-1].replace('\"', "")

            if temp != self.imageid:
                self.imageid = temp
                repeat = False

# This will staydisabled during the testing phase, in order to follow frames captured
#        for i in os.listdir("media/external/img"):  # remove all previous images
#            os.remove(i)
        urllib.urlretrieve(home_dir+self.imageid, self.imageid)         # get the last element from the list

    def get_image_id(self):
        return self.imageid


text:
'use strict';

// Vendor
var d3 = require('d3');
var _sortBy = require('lodash/collection/sortBy');
var _sortByOrder = require('lodash/collection/sortByOrder');
var _sum = require('lodash/math/sum');
var firstBy = require('thenby');
// Util
var SearchFormUtil = require('utils/SearchFormUtil/SearchFormUtil.js');

/**
 * This util is used to format aggregations to C3-style input data
 */
var FormatAggregationUtil = {
	/**
	 * Turn aggregations in to number of posts per year per org
	 * @param {Object} aggregations
	 * @return {Object}
	 */

	toOrgYearTimeSeries: function(aggregations) {
		var xs = {};
		var columns = [];
		// If there are any buckets on yars
		if(aggregations.org_per_year && aggregations.org_per_year.buckets && aggregations.org_per_year.buckets.length > 0) {
			var buckets = aggregations.org_per_year.buckets;
			// For each org
			buckets.map(function(bucket, i) {
				if(bucket.year) {
					var X = ['x_' + bucket.key];
					var Y = [bucket.key];
					xs[bucket.key] = 'x_' + bucket.key;
					// For each year in org
					bucket.year.buckets.map(function(year, j) {
						X.push(year.key);
						Y.push(year.doc_count);
					});
					columns.push(X);
					columns.push(Y);
				}
			});
		}
		var chart = {
			xs: xs,
			columns: columns,
		}
		return chart;
	},
	/**
	 * Turn aggregations in to number of docs per year
	 * @param {Object} aggregations
	 * @return {Object}
	 */
	toYearTimeSeries: function(aggregations) {
		var xs = {};
		var columns = [];
		// If there are any buckets on yars
		if(aggregations.year && aggregations.year.buckets && aggregations.year.buckets.length > 0) {
			var Y = ['Alla lärosäten'];
			var X = ['x_Alla lärosäten'];
			xs['Alla lärosäten'] = 'x_Alla lärosäten';
			// Sort by year
			aggregations.year.buckets = _sortBy(aggregations.year.buckets, function(p) {
				return p.key;
			});
			aggregations.year.buckets.map(function(bucket) {
				X.push(bucket.key);
				Y.push(bucket.doc_count);
			});
			columns.push(X);
			columns.push(Y);
		}
		return {
			xs: xs,
			columns: columns,
		}
	},
	/**
	 * Turn aggregations in to number of docs per org
	 * @param {Object} aggregations
	 * @return {Object}
	 */
	toOrgDistribution: function(aggregations, top) {
		var formattedData = []; // Data to be returned
		// If there are buckets on organisations
		if(aggregations.org && aggregations.org.buckets && aggregations.org.buckets.length > 0) {
			// Sort by n. of posts
			aggregations.org.buckets = _sortByOrder(aggregations.org.buckets, function(p) {
				return p.doc_count;
			}, ['desc']);
			// Show only top x
			top = top || 100000;
			aggregations.org.buckets.map(function(bucket, i) {
				if(i < top) {
					formattedData.push([bucket.key, bucket.doc_count]);
				} else if(i === top) {
					formattedData.push(['Övriga', bucket.doc_count]);
				} else {
					formattedData[top][1]++;
				}
			});
		}
		return {
			columns: formattedData
		}
	},
	/**
	 * Turn aggregations in to overall distribution of violations
	 * @param {Object} aggregations
	 * @return {Object}
	 */
	toViolationDistribution: function(aggregations) {
		var formattedData = []; // Data to be returned
		// If there are buckets on organisations
		if(aggregations.org && aggregations.org.buckets && aggregations.org.buckets.length > 0 && aggregations.missingViolations) {
			formattedData.push(['Bristfälliga poster']);
			aggregations.org.buckets.map(function(bucket, i) {
				formattedData[0].push(bucket.doc_count)
			});
			formattedData[0].push(-1*aggregations.missingViolations.doc_count);
			formattedData.push(['Felfria poster', aggregations.missingViolations.doc_count]);
		}
		return {
			columns: formattedData
		}
	},
	/**
	 * Turn aggregations in to violation ratio per org
	 * @param {Object} aggregations
	 * @return {Object}
	 */
	toOrgViolationRatio: function(aggregations, top) {
		var columns = [];
		var filler = [];
		var groups = [];
		top = top || 100000;
		var aggregate = aggregations.missing_violations_per_org;
		if(aggregate && aggregate.buckets) {
			aggregate.buckets = _sortByOrder(aggregate.buckets, function(bucket) {
				return bucket.missingViolations.doc_count / bucket.doc_count;
			}, ['desc']);
			aggregate.buckets.forEach(function(bucket) {
				var arr = [bucket.key];
				arr = arr.concat(filler);
				// Fill start with zeros
				filler.push(null);
				var val = (bucket.missingViolations.doc_count / bucket.doc_count);
				arr.push(val);
				columns.push(arr);
				groups.push(bucket.key);
			});
		}
		// Top 7
		columns = columns.slice(0, top);
		groups = groups.slice(0, top);
		// Fill tail with zeros
		columns.forEach(function(column) {
			var desiredLength = columns.length + 1;
			for(var i = column.length; i < desiredLength; i++) {
				column.push(null);
			}
		});
		var chart = {
			columns: columns,
			groups: [groups],
			categories: groups
		};

		return chart;
	},
	/**
	 * Turn aggregations into distribution over violation types
	 * @param {Object} aggregations
	 * @param {String} orgKey
	 * @return {Object}
	 */
	toViolationTypeDistributions: function(aggregations, orgKey) {
		var columns = [];
			if(aggregations.violations_per_org_per_year && aggregations.violations_per_org_per_year.buckets) {
				var violationTypes = aggregations.violations_per_org_per_year.buckets;
				violationTypes.forEach(function(violationType) {
					var key = violationType.key;
					columns.push([key]);
					if(violationType.org && violationType.org.buckets) {
						var orgs = violationType.org.buckets;
						orgs.forEach(function(org) {
							if(orgKey.length === 0 || orgKey.indexOf(org.key) !== -1) {
								columns[columns.length-1].push(org.doc_count);
							}
						});
					}
				});
		}
        // Sort the columns
        SearchFormUtil.getViolations(function(violations) { // Get grades
            var remap = {};
            Object.keys(violations).forEach(function(v) {
                remap[violations[v].name] = violations[v];
            });
            columns = columns.sort(
                firstBy(function(a, b) {
                    // Sort by grade
                    return remap[b[0]].grade - remap[a[0]].grade;
                })
                .thenBy(function(a, b) {
                    // Sort by sum
                    return _sum(b.slice(1,b.length-1)) - _sum(a.slice(1,a.length-1));
                })
            );
        });
        var chart = {
			columns: columns,
			donut: {
				label: {
					format: function (value, ratio) { return value; }
				}
			}
		};
		return chart;
	},
	/**
	 * Turn aggregations in to "Ratio of posts containing at least a grade 3 violation per org per year". If collapse is
	 * set to true, however, we collapse all org-curves in to one
	 * @param {Object} aggregations
	 * @param {Boolean} collapse
	 * @return {Object}
	 */
	toGrade3ViolationRatioYearTimeSeries: function(aggregations, collapse) {
		var xs = {};
		var columns = []; // One curve per org
		var collapsed = {}; // One curve for all orgs
		if(aggregations.violation_severity_per_org_per_year && aggregations.violation_severity_per_org_per_year.buckets) {
			var orgs = aggregations.violation_severity_per_org_per_year.buckets;
			// For every org
			orgs.forEach(function(org, i) {
				var X = ['x_' + org.key];
				var Y = [org.key];
				xs[org.key] = 'x_' + org.key;
				if(org.year && org.year.buckets) {
					var years = org.year.buckets;
					// For every year
					years.forEach(function(year) {
						if(year.severity && year.severity.buckets) {
							X.push(year.key);
							// Only look at severity == 3
							year.severity.buckets.forEach(function(severity) {
								if(severity.key === 3) {
									// Calc yearly ratio for one org
									if(!collapse) {
										Y.push(Math.round(severity.doc_count / year.doc_count * 100)/100);
									} else { // Sum values for all orgs
										if(collapsed[year.key]) {
											collapsed[year.key].docs += year.doc_count;
											collapsed[year.key].grade3s += severity.doc_count;
										} else {
											collapsed[year.key] = {
												docs: year.doc_count,
												grade3s: severity.doc_count
											}
										}
									}
								}
							});
							columns.push(X);
							columns.push(Y);
						}
					});
				}
			});
		}
		if(collapse) {
			columns = [];
			var X = ['x_Alla lärosäten'];
			var Y = ['Alla lärosäten']
			xs['Alla lärosäten'] = 'x_Alla lärosäten';
			Object.keys(collapsed).map(function(key) {
				X.push(key);
				Y.push(Math.round(collapsed[key].grade3s / collapsed[key].docs * 100)/100);
			});
			columns.push(X);
			columns.push(Y);
		}
		var chart = {
			xs: xs,
			columns: columns
		};
		return chart;
	}
};

module.exports = FormatAggregationUtil;


text:
<?php

namespace spec\TheWilkyBarKid\TextFilter\Adapter;

use HTMLPurifier;
use PhpSpec\ObjectBehavior;

class HTMLPurifierTextFilterAdapterSpec extends ObjectBehavior
{
    public function let(HTMLPurifier $htmlPurifier)
    {
        $this->beConstructedWith($htmlPurifier);
    }

    public function it_is_initializable()
    {
        $this->shouldHaveType('TheWilkyBarKid\TextFilter\Adapter\HTMLPurifierTextFilterAdapter');
        $this->shouldBeAnInstanceOf('TheWilkyBarKid\TextFilter\TextFilter');
    }

    public function it_filters_text(HTMLPurifier $htmlPurifier)
    {
        $htmlPurifier->purify('foo')->willReturn('bar');

        $this->filter('foo')->shouldReturn('bar');
    }

    public function it_should_throw_an_exception_on_a_failure(HTMLPurifier $htmlPurifier)
    {
        $htmlPurifier->purify('foo')->willReturn(false);

        $this->shouldThrow('TheWilkyBarKid\TextFilter\Exception\TextFilterFailedException')
          ->during('filter', array('foo'));
    }

    public function it_should_throw_an_exception_on_an_exception(HTMLPurifier $htmlPurifier)
    {
        $htmlPurifier->purify('bar')->willThrow('Exception');

        $this->shouldThrow('TheWilkyBarKid\TextFilter\Exception\TextFilterFailedException')
          ->during('filter', array('foo'));
    }

    public function it_should_reject_non_strings()
    {
        foreach (array(1, false, $this) as $test) {
            $this->shouldThrow('InvalidArgumentException')->during('filter', array($test));
        }
    }
}


text:
import clog

# check that we're not accidentally testing the packaged clog
assert not clog.__file__.startswith('/usr')


text:
const options: CodeMirror.TernOptions = {

    completionTip: (data) => {
        const d = data.completions;
        return "";
    },

    showError: (editor, message) => {
        alert(message);
    }

};

const ts = new CodeMirror.TernServer(options);

ts.request(cm.getDoc(), "completions", (_e, d) => {
    if (d) {
        const c = d.completions;
    }
}, { ch: 0, line: 0 });

ts.complete(cm.getDoc());

ts.showType(cm.getDoc());


text:
package com.dremio.service.jobs;

import static com.google.common.base.Preconditions.checkNotNull;
import static java.lang.String.format;

import java.util.Collections;
import java.util.List;
import java.util.concurrent.CopyOnWriteArrayList;

import com.dremio.common.utils.PathUtils;
import com.dremio.service.job.proto.JobAttempt;
import com.dremio.service.job.proto.JobId;
import com.dremio.service.job.proto.JobResult;
import com.dremio.service.job.proto.SessionId;
import com.google.common.base.Objects;
import com.google.common.base.Preconditions;

/**
 * Job represents details of a currently running or completed query on a dataset.
 */
public class Job {

  private final JobId jobId;
  private final SessionId sessionId;
  private final List<JobAttempt> attempts = new CopyOnWriteArrayList<>();
  private final JobResultsStore resultsStore;
  private volatile long recordCount;
  private volatile boolean isInternal;

  private JobData data;
  /**
   * true when all attempts complete.
   * This is necessary as we cant' just rely on the last attempt's state in case the query reattempts
   */
  private boolean completed;

  public Job(JobId jobId, JobAttempt jobAttempt, SessionId sessionId) {
    this.jobId = jobId;
    this.sessionId = sessionId;
    this.resultsStore = null;
    this.completed = false;
    attempts.add( checkNotNull(jobAttempt, "jobAttempt is null"));
  }

  /**
   * Create an instance which loads the job results lazily.
   * @param jobId
   * @param jobResult
   * @param resultsStore
   * @param sessionId
   */
  public Job(JobId jobId, JobResult jobResult, JobResultsStore resultsStore, SessionId sessionId) {
    this.jobId = jobId;
    this.sessionId = sessionId;
    this.attempts.addAll(jobResult.getAttemptsList());
    this.resultsStore = checkNotNull(resultsStore);
    this.completed = jobResult.getCompleted();
  }

  void setRecordCount(long recordCount) {
    this.recordCount = recordCount;
  }

  long getRecordCount() {
    return this.recordCount;
  }

  public JobId getJobId() {
    return jobId;
  }

  public SessionId getSessionId() {
    return sessionId;
  }

  public JobAttempt getJobAttempt() {
    Preconditions.checkState(attempts.size() >=1, "There should be at least one attempt in Job");
    int lastAttempt = attempts.size() - 1;
    return attempts.get(lastAttempt);
  }

  void addAttempt(final JobAttempt jobAttempt) {
    attempts.add(jobAttempt);
  }

  public List<JobAttempt> getAttempts() {
    return Collections.unmodifiableList(attempts);
  }

  @Override
  public String toString() {
    final JobAttempt jobAttempt = getJobAttempt();
    final String sessionIdStr = sessionId == null ? null : sessionId.getId();
    return format("{JobId: %s, SessionId: %s, SQL: %s, Dataset: %s, DatasetVersion: %s}",
            jobId.getId(), sessionIdStr, jobAttempt.getInfo().getSql(),
            PathUtils.constructFullPath(jobAttempt.getInfo().getDatasetPathList()),
            jobAttempt.getInfo().getDatasetVersion()); //todo
  }

  public JobData getData(){
    Preconditions.checkState(data != null || resultsStore != null, "not available from deserialized Job");
    if (data != null) {
      return data;
    }
    return resultsStore.get(getJobId(), getSessionId());
  }

  void setData(JobData data){
    Preconditions.checkArgument(this.data == null);
    this.data = data;
  }

  public boolean isCompleted() {
    return completed;
  }

  void setCompleted(boolean completed) {
    this.completed = completed;
  }

  /**
   * Check if this Job has results. Job results may exist for FAILED jobs. Users
   * should be aware and check JobState if necessary.
   */
  public boolean hasResults() {
    return resultsStore != null && resultsStore.jobOutputDirectoryExists(jobId);
  }

  void setIsInternal(boolean isInternal) {
    this.isInternal = isInternal;
  }

  boolean isInternal() {
    return isInternal;
  }

  @Override
  public int hashCode() {
    return Objects.hashCode(jobId, attempts, completed, sessionId);
  }

  @Override
  public boolean equals(Object obj) {
    if (obj != null) {
      if (obj instanceof Job) {
        Job other = (Job) obj;
        return Objects.equal(jobId, other.jobId) &&
          Objects.equal(attempts, other.attempts) &&
          Objects.equal(completed, other.completed) &&
          Objects.equal(sessionId, other.sessionId);
      }
    }
    return false;
  }

  JobResult toJobResult(Job job) {
    JobResult jobResult = new JobResult()
      .setCompleted(completed)
      .setAttemptsList(job.getAttempts());
    if (sessionId != null) {
      jobResult.setSessionId(sessionId);
    }
    return jobResult;
  }

}


text:
package org.apache.ignite.cache.hibernate;

import java.util.Collections;
import javax.cache.configuration.Factory;
import javax.transaction.Synchronization;
import javax.transaction.TransactionManager;
import javax.transaction.UserTransaction;
import org.apache.commons.dbcp.managed.BasicManagedDataSource;
import org.apache.ignite.configuration.CacheConfiguration;
import org.apache.ignite.configuration.IgniteConfiguration;
import org.h2.jdbcx.JdbcDataSource;
import org.hibernate.boot.registry.StandardServiceRegistryBuilder;
import org.hibernate.cache.spi.access.AccessType;
import org.hibernate.cfg.Environment;
import org.hibernate.engine.jdbc.connections.internal.DatasourceConnectionProviderImpl;
import org.hibernate.engine.jdbc.connections.spi.ConnectionProvider;
import org.hibernate.engine.transaction.jta.platform.internal.AbstractJtaPlatform;
import org.hibernate.engine.transaction.jta.platform.spi.JtaPlatform;
import org.hibernate.resource.transaction.backend.jta.internal.JtaTransactionCoordinatorBuilderImpl;
import org.jetbrains.annotations.Nullable;
import org.objectweb.jotm.Jotm;

/**
 *
 * Tests Hibernate L2 cache with TRANSACTIONAL access mode (Hibernate and Cache are configured
 * to used the same TransactionManager).
 */
public class HibernateL2CacheTransactionalSelfTest extends HibernateL2CacheSelfTest {
    /** */
    private static Jotm jotm;

    /**
     */
    private static class TestJtaPlatform extends AbstractJtaPlatform {
        /** {@inheritDoc} */
        @Override protected TransactionManager locateTransactionManager() {
            return jotm.getTransactionManager();
        }

        /** {@inheritDoc} */
        @Override protected UserTransaction locateUserTransaction() {
            return jotm.getUserTransaction();
        }
    }

    /**
     */
    @SuppressWarnings("PublicInnerClass")
    public static class TestTmFactory implements Factory<TransactionManager> {
        /** */
        private static final long serialVersionUID = 0;

        /** {@inheritDoc} */
        @Override public TransactionManager create() {
            return jotm.getTransactionManager();
        }
    }

    /** {@inheritDoc} */
    @Override protected void beforeTestsStarted() throws Exception {
        jotm = new Jotm(true, false);

        super.beforeTestsStarted();
    }

    /** {@inheritDoc} */
    @Override protected void afterTestsStopped() throws Exception {
        if (jotm != null)
            jotm.stop();

        jotm = null;
    }

    /** {@inheritDoc} */
    @Override protected IgniteConfiguration getConfiguration(String igniteInstanceName) throws Exception {
        IgniteConfiguration cfg = super.getConfiguration(igniteInstanceName);

        cfg.getTransactionConfiguration().setTxManagerFactory(new TestTmFactory());
        cfg.getTransactionConfiguration().setUseJtaSynchronization(useJtaSynchronization());

        return cfg;
    }

    /** {@inheritDoc} */
    @Override protected CacheConfiguration transactionalRegionConfiguration(String regionName) {
        CacheConfiguration cfg = super.transactionalRegionConfiguration(regionName);

        cfg.setNearConfiguration(null);

        return cfg;
    }

    /** {@inheritDoc} */
    @Nullable @Override protected StandardServiceRegistryBuilder registryBuilder() {
        StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder();

        DatasourceConnectionProviderImpl connProvider = new DatasourceConnectionProviderImpl();

        BasicManagedDataSource dataSrc = new BasicManagedDataSource(); // JTA-aware data source.

        dataSrc.setTransactionManager(jotm.getTransactionManager());

        dataSrc.setDefaultAutoCommit(false);

        JdbcDataSource h2DataSrc = new JdbcDataSource();

        h2DataSrc.setURL(CONNECTION_URL);

        dataSrc.setXaDataSourceInstance(h2DataSrc);

        connProvider.setDataSource(dataSrc);

        connProvider.configure(Collections.emptyMap());

        builder.addService(ConnectionProvider.class, connProvider);

        builder.addService(JtaPlatform.class, new TestJtaPlatform());

        builder.applySetting(Environment.TRANSACTION_COORDINATOR_STRATEGY, JtaTransactionCoordinatorBuilderImpl.class.getName());

        return builder;
    }

    /** {@inheritDoc} */
    @Override protected AccessType[] accessTypes() {
        return new AccessType[]{AccessType.TRANSACTIONAL};
    }

    /**
     * @return Whether to use {@link Synchronization}.
     */
    protected boolean useJtaSynchronization() {
        return false;
    }
}


text:
package es.gob.afirma.miniapplet;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.security.AccessController;
import java.security.KeyStore.PrivateKeyEntry;
import java.security.MessageDigest;
import java.security.PrivilegedActionException;
import java.security.PrivilegedExceptionAction;
import java.security.cert.CertificateEncodingException;
import java.util.Locale;
import java.util.Properties;
import java.util.logging.Logger;

import javax.swing.JApplet;
import javax.swing.UIManager;

import org.mozilla.universalchardet.UniversalDetector;

import com.dmurph.tracking.AnalyticsConfigData;
import com.dmurph.tracking.JGoogleAnalyticsTracker;
import com.dmurph.tracking.JGoogleAnalyticsTracker.GoogleAnalyticsVersion;

import es.gob.afirma.core.AOCancelledOperationException;
import es.gob.afirma.core.AOException;
import es.gob.afirma.core.AOFormatFileException;
import es.gob.afirma.core.LogManager;
import es.gob.afirma.core.LogManager.App;
import es.gob.afirma.core.misc.Base64;
import es.gob.afirma.core.misc.Platform;
import es.gob.afirma.core.signers.AOSignConstants;
import es.gob.afirma.core.signers.AOSigner;
import es.gob.afirma.crypto.jarverifier.JarSignatureCertExtractor;
import es.gob.afirma.keystores.AOKeyStore;
import es.gob.afirma.keystores.filters.CertFilterManager;
import es.gob.afirma.miniapplet.ExtraParamsProcessor.IncompatiblePolicyException;

/** MiniApplet de firma del proyecto Afirma. */
public final class MiniAfirmaApplet extends JApplet implements MiniAfirma {

	private static final long serialVersionUID = -4364574240099120486L;

	private static final Logger LOGGER = Logger.getLogger("es.gob.afirma"); //$NON-NLS-1$

	private static final String GOOGLE_ANALYTICS_TRACKING_CODE = "UA-41615516-2"; //$NON-NLS-1$

	private static final String EOF = "%%EOF%%"; //$NON-NLS-1$
	private static final String DEFAULT_CHUNK_ENCODING = "ISO-8859-1";  //$NON-NLS-1$

	private static final String APPLET_PARAM_USER_AGENT = "userAgent"; //$NON-NLS-1$

	private static final String APPLET_PARAM_SYSTEM_PROPERTIES = "system_properties"; //$NON-NLS-1$

	private static final String APPLET_PARAM_LOCALE = "locale"; //$NON-NLS-1$

	private static final String APPLET_PARAM_USER_KEYSTORE = "keystore"; //$NON-NLS-1$

	private static final String SIGNATURE_FORMAT_AUTO = "AUTO"; //$NON-NLS-1$

	/** Número máximo de caracteres que se devuelven en cualquiera de los
	 * métodos del Applet. */
	private static final int BUFFER_SIZE = 1024 * 1024;	// 1 Mb

	private final StringBuilder dataStore = new StringBuilder();

	/** Flujo de datos utilizado para la lectura de datos en fragmentos. */
	private InputStream chunkedReturnStream;

	/** Clave privada fijada para reutilizarse en operaciones sucesivas. */
	private PrivateKeyEntry stickyKeyEntry = null;

	private boolean stickySignatory = false;

	/** Identificador del navegador Web que carga el applet. */
	private String userAgent = null;

	/** Tipo de almacén de claves del que extraer los certificados. */
	private AOKeyStore keystoreType = null;

	/** Ruta de la biblioteca o almacén del que extraer los certificados. */
	private String keystoreLib = null;

	/** Mensaje del último error producido. */
	private String errorMessage = null;

	/** Tipoe del último error producido. */
	private String errorType = null;

	static {
		try {
			LogManager.install(App.MINIAPPLET);
		}
		catch(final Exception e) {
			Logger.getLogger("es.gob.afirma").severe("No ha sido posible instalar el gestor de registro: " + e); //$NON-NLS-1$ //$NON-NLS-2$
		}
	}

	/** {@inheritDoc} */
	@Override
	public void setStickySignatory(final boolean sticky) {
		this.stickySignatory = sticky;
		if (!sticky) {
			this.stickyKeyEntry = null;
		}
	}

	/** {@inheritDoc} */
	@Override
	public String sign(final String algorithm,
					   final String format,
					   final String extraParams) throws PrivilegedActionException,
			                                            IOException,
			                                            AOException,
			                                            CertificateEncodingException,
			                                            IncompatiblePolicyException {

		LOGGER.info("Solicitada firma con algoritmo " + algorithm + " y formato " + format); //$NON-NLS-1$ //$NON-NLS-2$

		this.clearError();

		byte[] dataBinary;
		if (this.dataStore.length() > 0) {
			try {
				dataBinary = Base64.decode(this.dataStore.toString());
			}
			catch (final IOException e) {
				setError(e, "Los datos proporcionados est\u00E1n mal codificados en base 64"); //$NON-NLS-1$
				throw e;
			}
			catch (final OutOfMemoryError e) {
				setError(e, "Error de falta de memoria durante la carga de los datos"); //$NON-NLS-1$
				throw e;
			}
			finally {
				this.dataStore.setLength(0);
			}
		}
		else {
			try {
				dataBinary = AccessController.doPrivileged(new GetFileContentAction(
						MiniAppletMessages.getString("MiniAfirmaApplet.0"), null, //$NON-NLS-1$
						MiniAppletMessages.getString("MiniAfirmaApplet.1"), this)); //$NON-NLS-1$
			}
			catch (final AOCancelledOperationException e) {
				setError(e);
				throw e;
			}
			catch (final java.util.concurrent.CancellationException e) {
				final AOCancelledOperationException ce = new AOCancelledOperationException("Operacion cancelada por el usuario", e); //$NON-NLS-1$
				setError(ce);
				throw ce;
			}
			catch (final PrivilegedActionException e) {
				setError(e);
				throw e;
			}
			catch (final OutOfMemoryError e) {
				setError(e, "Error de falta de memoria durante la carga del fichero de datos"); //$NON-NLS-1$
				throw e;
			}
			catch (final Error e) {
				setError(e);
				throw e;
			}
		}

		final Properties params = ExtraParamsProcessor.convertToProperties(extraParams);

		// Informacion sobre los parametros adicionales indicados
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		final PrintStream ps = new PrintStream(baos);
		params.list(ps);
		LOGGER.info("Recibidos los siguientes parametros adicionales:\n" + baos.toString()); //$NON-NLS-1$

		try {
			String signatureFormat = MiniAfirmaApplet.cleanParam(format);
			final AOSigner signer = MiniAfirmaApplet.selectSigner(signatureFormat, null);
			if (SIGNATURE_FORMAT_AUTO.equalsIgnoreCase(signatureFormat)) {
				signatureFormat = ExtraParamsProcessor.getSignFormat(signer);
				ExtraParamsProcessor.configAutoFormat(signer, dataBinary, params);
			}

			// XXX: Codigo para la identificacion de firmas XAdES enveloped explicita
			// (Eliminar cuando se abandone el soporte de XAdES explicitas)
			if (isXadesEnvelopedExplicit(signatureFormat, params)) {
				final IllegalArgumentException e = new IllegalArgumentException(
						"El formato Enveloped es incompatible con el modo de firma explicito"); //$NON-NLS-1$
				setError(e);
				throw e;
			}

			// XXX: Codigo de soporte de firmas XAdES explicitas (Eliminar cuando se abandone el soporte de XAdES explicitas)
			if (isXadesExplicitConfigurated(signatureFormat, params)) {
				try {
					dataBinary = MessageDigest.getInstance("SHA1").digest(dataBinary); //$NON-NLS-1$
					params.setProperty("mimeType", "hash/sha1"); //$NON-NLS-1$ //$NON-NLS-2$
				} catch (final Exception e) {
					LOGGER.warning("Error al generar la huella digital de los datos para firmar como 'XAdES explicit', " //$NON-NLS-1$
							+ "se realizara una firma XAdES corriente: " + e); //$NON-NLS-1$
				}
			}

			final PrivateKeyEntry pke = this.selectPrivateKey(params);
			final byte[] signature = AccessController.doPrivileged(
					new SignAction(
						signer,
						dataBinary,
						MiniAfirmaApplet.cleanParam(algorithm),
						pke,
						ExtraParamsProcessor.expandProperties(params, dataBinary, signatureFormat)
					)
				);

			// El base 64 es un 30% mayor que los datos originales, asi que calculamos el tamano al alza en base al tamano de la firma
			// (normalmente mayor que el del certificado)
			final StringBuilder result = new StringBuilder((int) Math.floor(signature.length * 1.4));
			return chunkReturn(
				result.
					append(Base64.encode(pke.getCertificate().getEncoded())).
					append('|').
					append(Base64.encode(signature)).toString()
			);
		}
		catch (final IncompatiblePolicyException e) {
			setError(e);
			throw e;
		}
		catch (final AOFormatFileException e) {
			setError(e);
			throw e;
		}
		catch (final CertificateEncodingException e) {
			setError(e);
			throw e;
		}
		catch (final PrivilegedActionException e) {
			setError(e);
			throw e;
		}
		catch (final RuntimeException e) {
			setError(e);
			throw e;
		}
		catch (final OutOfMemoryError e) {
			setError(e, "Error de falta de memoria durante la operaci\u00F3n de firma"); //$NON-NLS-1$
			throw e;
		}
		catch (final Error e) {
			setError(e);
			throw new AOException("Ocurrio un error grave durante la operaci\u00F3n de firma", e); //$NON-NLS-1$
		}

	}

	/** {@inheritDoc} */
	@Override
	public String coSign(final String dataB64,
			             final String algorithm,
			             final String format,
			             final String extraParams) throws PrivilegedActionException,
			             							      IOException,
				                                          AOException,
				                                          CertificateEncodingException,
				                                          IncompatiblePolicyException {
		this.clearError();

		byte[] signature;
		if (this.dataStore.length() > 0) {
			try {
				signature = Base64.decode(this.dataStore.toString());
			}
			catch (final IOException e) {
				setError(e, "La firma proporcionada est\u00E1 mal codificada en base 64"); //$NON-NLS-1$
				throw e;
			}
			catch (final OutOfMemoryError e) {
				setError(e, "Error de falta de memoria durante la carga de la firma"); //$NON-NLS-1$
				throw e;
			}
			finally {
				this.dataStore.setLength(0);
			}
		}
		else {
			try {
				signature = AccessController.doPrivileged(new GetFileContentAction(
						MiniAppletMessages.getString("MiniAfirmaApplet.2"), null, //$NON-NLS-1$
						MiniAppletMessages.getString("MiniAfirmaApplet.1"), this)); //$NON-NLS-1$
			}
			catch (final AOCancelledOperationException e) {
				setError(e);
				throw e;
			}
			catch (final java.util.concurrent.CancellationException e) {
				final AOCancelledOperationException ce = new AOCancelledOperationException("Operacion cancelada por el usuario", e); //$NON-NLS-1$
				setError(ce);
				throw ce;
			}
			catch (final OutOfMemoryError e) {
				setError(e, "Error de falta de memoria durante la carga del fichero de firma"); //$NON-NLS-1$
				throw e;
			}
			catch (final PrivilegedActionException e) {
				setError(e);
				throw e;
			}
			catch (final Error e) {
				setError(e);
				throw new AOException("Ocurrio un error grave durante la operaci\u00F3n de firma", e); //$NON-NLS-1$
			}
		}

		final Properties params = ExtraParamsProcessor.convertToProperties(extraParams);
		final byte[] dataBinary;
		try {
			dataBinary = dataB64 == null ? null : Base64.decode(dataB64);
		}
		catch (final IOException e) {
			setError(e, "Los datos proporcionados est\u00E1n mal codificados en base 64"); //$NON-NLS-1$
			throw e;
		}
		catch (final OutOfMemoryError e) {
			setError(e, "Error de falta de memoria durante la carga de los datos"); //$NON-NLS-1$
			throw e;
		}
		catch (final Error e) {
			setError(e);
			throw new AOException("Ocurrio un error grave durante la operaci\u00F3n de firma", e); //$NON-NLS-1$
		}

		try {
			String signatureFormat = format;
			final AOSigner signer = MiniAfirmaApplet.selectSigner(MiniAfirmaApplet.cleanParam(signatureFormat), signature);
			if (SIGNATURE_FORMAT_AUTO.equalsIgnoreCase(signatureFormat)) {
				signatureFormat = ExtraParamsProcessor.getSignFormat(signer);
				ExtraParamsProcessor.configAutoFormat(signer, signature, params);
			}

			final PrivateKeyEntry pke = this.selectPrivateKey(params);
			final byte[] cosignature = AccessController.doPrivileged(
				new CoSignAction(
					signer,
					signature,
					dataBinary,
					MiniAfirmaApplet.cleanParam(algorithm),
					pke,
					ExtraParamsProcessor.expandProperties(params, dataBinary, signatureFormat)
				)
			);

			// El base 64 es un 30% mayor que los datos originales, asi que calculamos el tamano al alza en base al tamano de la firma
			// (normalmente mayor que el del certificado)
			final StringBuilder result = new StringBuilder((int) Math.floor(cosignature.length * 1.4));
			return chunkReturn(result.
				append(Base64.encode(pke.getCertificate().getEncoded())).
				append('|').
				append(Base64.encode(cosignature)).toString()
			);

		}
		catch (final IncompatiblePolicyException e) {
			setError(e);
			throw e;
		}
		catch (final AOFormatFileException e) {
			setError(e);
			throw e;
		}
		catch (final PrivilegedActionException e) {
			setError(e);
			throw e;
		}
		catch (final CertificateEncodingException e) {
			setError(e);
			throw e;
		}
		catch (final RuntimeException e) {
			setError(e);
			throw e;
		}
		catch (final OutOfMemoryError e) {
			setError(e, "Error de falta de memoria durante la operaci\u00F3n de cofirma"); //$NON-NLS-1$
			throw e;
		}
		catch (final Error e) {
			setError(e);
			throw new AOException("Ocurrio un error grave durante la operaci\u00F3n de cofirma", e); //$NON-NLS-1$
		}
	}

	/** {@inheritDoc} */
	@Override
	public String counterSign(final String algorithm,
			                  final String format,
			                  final String extraParams) throws PrivilegedActionException,
			                  								   IOException,
					                                           AOException,
					                                           CertificateEncodingException,
					                                           IncompatiblePolicyException {
		this.clearError();

		byte[] signature;
		if (this.dataStore.length() > 0) {
			try {
				signature = Base64.decode(this.dataStore.toString());
			}
			catch (final IOException e) {
				setError(e, "La firma proporcionada est\u00E1 mal codificada en base 64"); //$NON-NLS-1$
				throw e;
			}
			catch (final OutOfMemoryError e) {
				setError(e, "Error de falta de memoria durante la carga de la firma"); //$NON-NLS-1$
				throw e;
			}
			finally {
				this.dataStore.setLength(0);
			}
		}
		else {
			try {
				signature = AccessController.doPrivileged(new GetFileContentAction(
						MiniAppletMessages.getString("MiniAfirmaApplet.2"), null, //$NON-NLS-1$
						MiniAppletMessages.getString("MiniAfirmaApplet.1"), this)); //$NON-NLS-1$
			}
			catch (final AOCancelledOperationException e) {
				setError(e);
				throw e;
			}
			catch (final java.util.concurrent.CancellationException e) {
				final AOCancelledOperationException ce = new AOCancelledOperationException("Operacion cancelada por el usuario", e); //$NON-NLS-1$
				setError(ce);
				throw ce;
			}
			catch (final PrivilegedActionException e) {
				setError(e);
				throw e;
			}
			catch (final OutOfMemoryError e) {
				setError(e, "Error de falta de memoria durante la carga del fichero de firma"); //$NON-NLS-1$
				throw e;
			}
		}

		final Properties params = ExtraParamsProcessor.convertToProperties(extraParams);

		try {
			String signatureFormat = format;
			final AOSigner signer = MiniAfirmaApplet.selectSigner(MiniAfirmaApplet.cleanParam(signatureFormat), signature);
			if (SIGNATURE_FORMAT_AUTO.equalsIgnoreCase(signatureFormat)) {
				signatureFormat = ExtraParamsProcessor.getSignFormat(signer);
				ExtraParamsProcessor.configAutoFormat(signer, signature, params);
			}

			final PrivateKeyEntry pke = this.selectPrivateKey(params);
			final byte[] countersignature = AccessController.doPrivileged(
				new CounterSignAction(
						signer,
						signature,
						MiniAfirmaApplet.cleanParam(algorithm),
						pke,
						ExtraParamsProcessor.expandProperties(params, null, signatureFormat)
				)
			);

			// El base 64 es un 30% mayor que los datos originales, asi que calculamos el tamano al alza en base al tamano de la firma
			// (normalmente mayor que el del certificado)
			final StringBuilder result = new StringBuilder((int) Math.floor(countersignature.length * 1.4));
			return chunkReturn(result.
					append(Base64.encode(pke.getCertificate().getEncoded())).
					append('|').
					append(Base64.encode(countersignature)).toString());
		}
		catch (final IncompatiblePolicyException e) {
			setError(e);
			throw e;
		}
		catch (final AOFormatFileException e) {
			setError(e);
			throw e;
		}
		catch (final PrivilegedActionException e) {
			setError(e);
			throw e;
		}
		catch (final CertificateEncodingException e) {
			setError(e);
			throw e;
		}
		catch (final RuntimeException e) {
			setError(e);
			throw e;
		}
		catch (final OutOfMemoryError e) {
			setError(e, "Error de falta de memoria durante la operaci\u00F3n de contrafirma"); //$NON-NLS-1$
			throw e;
		}
		catch (final Error e) {
			setError(e);
			throw new AOException("Ocurrio un error grave durante la operaci\u00F3n de contrafirma", e); //$NON-NLS-1$
		}
	}

	/** {@inheritDoc} */
	@Override
	public boolean saveDataToFile(final String title,
			                      final String fileName,
			                      final String extension,
			                      final String description) throws PrivilegedActionException,
			                                                       IOException {
		this.clearError();

		if (this.dataStore.length() < 1) {
			LOGGER.warning(
				"Se ha solicitado guardar en disco un contenido nulo, se ignorara la peticion" //$NON-NLS-1$
			);
			return false;
		}

		final String titleDialog = MiniAfirmaApplet.cleanParam(title);

		final String depuredExts = MiniAfirmaApplet.cleanParam(extension);
		final String[] exts = depuredExts == null ? null : new String[] { depuredExts };

		final String descFiles = MiniAfirmaApplet.cleanParam(description);

		try {
			AccessController.doPrivileged(
				new SaveFileAction(
						titleDialog,
						Base64.decode(this.dataStore.toString()),
						exts,
						descFiles,
						MiniAfirmaApplet.cleanParam(fileName),
						this
				)
			);
			return true;
		}
		catch (final AOCancelledOperationException e) {
			return false;
		}
		catch (final java.util.concurrent.CancellationException e) {
			return false;
		}
		catch (final IOException e) {
			setError(e, "Los datos proporcionados est\u00E1n mal codificados en base 64"); //$NON-NLS-1$
			throw e;
		}
		catch (final PrivilegedActionException e) {
			setError(e);
			throw e;
		}
		catch (final RuntimeException e) {
			setError(e);
			throw e;
		}
		finally {
			this.dataStore.setLength(0);
		}
	}

	/** {@inheritDoc} */
	@Override
	public String getFileNameContentBase64(final String title,
			                               final String extensions,
			                               final String description,
			                               final String filePath) throws PrivilegedActionException, IOException {
		this.clearError();
		// Se llama a setError() desde getFileNameContent, si es preciso, por lo qye no es necesario repetirlo aqui
		return chunkReturn(this.getFileNameContent(title, extensions, description, filePath, true));
	}

	/** Permite seleccionar al usuario un fichero y devuelve la tupla con el
	 * nombre de fichero y su contenido separados por ('|').
	 * @param title Título de la ventana de selección.
	 * @param extensions Extensiones de fichero permitidas separadas por coma (',').
	 * @param description Descripción del tipo de fichero.
	 * @param filePath Ruta por defecto.
	 * @param asBase64 Si es {@code true} devuelve el contenido en Base64, si es {@code false}
	 * 				lo devuelve en texto plano.
	 * @return Tuplas "NombreFichero|Contenido".
	 * @throws PrivilegedActionException Cuando ocurre algún error durante la operación.
	 */
	private String getFileNameContent(final String title,
			                          final String extensions,
			                          final String description,
		                              final String filePath,
			                          final boolean asBase64) throws PrivilegedActionException {

		this.clearError();

		final String titleDialog = MiniAfirmaApplet.cleanParam(title);
		final String cleanExts = MiniAfirmaApplet.cleanParam(extensions);
		final String[] exts = cleanExts == null ? null : cleanExts.split(","); //$NON-NLS-1$
		final String descFiles = MiniAfirmaApplet.cleanParam(description);
		final String path = MiniAfirmaApplet.cleanParam(filePath);

		try {
			return AccessController.doPrivileged(new GetFileNameContentAction(
					titleDialog, exts, descFiles, path, false, asBase64, this))[0];
		}
		catch (final AOCancelledOperationException e) {
			setError(e);
			throw e;
		}
		catch (final java.util.concurrent.CancellationException e) {
			final AOCancelledOperationException ce = new AOCancelledOperationException("Operacion cancelada por el usuario", e); //$NON-NLS-1$
			setError(ce);
			throw ce;
		}
		catch (final PrivilegedActionException e) {
			setError(e);
			throw e;
		}
		catch (final RuntimeException e) {
			setError(e);
			throw e;
		}
		catch (final OutOfMemoryError e) {
			setError(e, "Error de falta de memoria durante la carga del fichero"); //$NON-NLS-1$
			throw e;
		}
	}

	/** {@inheritDoc} */
	@Override
	public String[] getMultiFileNameContentBase64(final String title,
			                                      final String extensions,
			                                      final String description,
			                                      final String filePath) throws IOException,
			                                                                       PrivilegedActionException {
		return this.getMultiFileNameContent(title, extensions, description, filePath,true);
	}

	/** Permite seleccionar al usuario un conjunto de ficheros y devuelve las tuplas con cada
	 * nombre de fichero y contenido separados por ('|').
	 * @param title Título de la ventana de selección.
	 * @param extensions Extensiones de fichero permitidas separadas por coma (',').
	 * @param description Descripción del tipo de fichero.
	 * @param filePath Ruta por defecto.
	 * @param asBase64 Si es {@code true} devuelve el contenido en Base64, si es {@code false}
	 * 				lo devuelve en texto plano.
	 * @return Listado de tuplas "NombreFichero|Contenido".
	 * @throws PrivilegedActionException Cuando ocurre algún error durante la operación.
	 */
	private String[] getMultiFileNameContent(final String title,
			                                 final String extensions,
			                                 final String description,
			                                 final String filePath,
			                                 final boolean asBase64) throws PrivilegedActionException {
		this.clearError();

		final String titleDialog = MiniAfirmaApplet.cleanParam(title);
		final String cleanExts = MiniAfirmaApplet.cleanParam(extensions);
		final String[] exts = cleanExts == null ? null : cleanExts.split(","); //$NON-NLS-1$
		final String descFiles = MiniAfirmaApplet.cleanParam(description);
		final String path = MiniAfirmaApplet.cleanParam(filePath);

		try {
			return AccessController.doPrivileged(new GetFileNameContentAction(
					titleDialog, exts, descFiles, path, true, asBase64, this));
		}
		catch (final AOCancelledOperationException e) {
			setError(e);
			throw e;
		}
		catch (final java.util.concurrent.CancellationException e) {
			final AOCancelledOperationException ce = new AOCancelledOperationException("Operacion cancelada por el usuario", e); //$NON-NLS-1$
			setError(ce);
			throw ce;
		}
		catch (final PrivilegedActionException e) {
			setError(e);
			throw e;
		}
		catch (final RuntimeException e) {
			setError(e);
			throw e;
		}
		catch (final OutOfMemoryError e) {
			setError(e, "Error de falta de memoria durante la carga de los ficheros"); //$NON-NLS-1$
			throw e;
		}
	}

	/** {@inheritDoc} */
	@Override
	public String getTextFromBase64(final String base64Data, final String charset) throws IOException {
		this.clearError();
		if (base64Data == null) {
			return null;
		}
		final String cleanCharset = getCharset(MiniAfirmaApplet.cleanParam(charset), base64Data);
		try {
			return chunkReturn(new String(Base64.decode(base64Data), cleanCharset));
		}
		catch (final IOException e) {
			setError(e);
			throw e;
		}
	}

	/** {@inheritDoc} */
	@Override
	public String getBase64FromText(final String plainText, final String charset) throws UnsupportedEncodingException {
		this.clearError();
		if (plainText == null) {
			return null;
		}
		final String cleanCharset = getCharset(
			MiniAfirmaApplet.cleanParam(charset),
			null
		);
		try {
			return Base64.encode(plainText.getBytes(cleanCharset));
		}
		catch (final UnsupportedEncodingException e) {
			setError(e);
			throw e;
		}
	}

	/** Obtiene la URL base del Applet.
	 * Al contrario que el <a href="http://docs.oracle.com/javase/7/docs/api/java/applet/Applet.html#getCodeBase%28%29">método original</a>,
	 * este funciona incluso en despliegues locales (<a href="http://bugs.java.com/bugdatabase/view_bug.do?bug_id=8017250">Bug 8017250 de Java</a>). */
	@Override
	public URL getCodeBase() {
		URL codebase = null;
		try {
			codebase = super.getCodeBase();
		}
		catch (final Exception e) { /* Ignorada */ }
		if (codebase != null) {
			return codebase;
		}
		try {
			return new URL(
				MiniAfirmaApplet.class.getResource("/miniappletmessages.properties").toString().replace("/miniappletmessages.properties", "") //$NON-NLS-1$ //$NON-NLS-2$ //$NON-NLS-3$
			);
		}
		catch (final MalformedURLException e) {
			throw new IllegalStateException("No se puede determinar el codebase del Aeplet: " + e, e); //$NON-NLS-1$
		}
	}

	/** {@inheritDoc} */
	@Override
	public void init() {

//		// Establecemos propiedades del sistema en base a argumentos de Java
		setSystemProperties(this.getParameter(APPLET_PARAM_SYSTEM_PROPERTIES));

		// Establecemos la localizacion
		setLocale(this.getParameter(APPLET_PARAM_LOCALE));

		// Configuramos el almacen en base al navegador
		this.userAgent = this.getParameter(APPLET_PARAM_USER_AGENT);

		final String keystoreParam = MiniAfirmaApplet.cleanParam(
			this.getParameter(APPLET_PARAM_USER_KEYSTORE)
		);
		if (keystoreParam != null && !keystoreParam.equals("null")) { //$NON-NLS-1$
			final int separatorPos = keystoreParam.indexOf(':');
			try {
				if (separatorPos == -1) {
					this.keystoreType = AOKeyStore.valueOf(keystoreParam);
				}
				else if (keystoreParam.length() > 1) {
					this.keystoreType = AOKeyStore.valueOf(keystoreParam.substring(0, separatorPos).trim());
					if (separatorPos < keystoreParam.length() -1 &&
							keystoreParam.substring(separatorPos + 1).trim().length() > 0) {
						this.keystoreLib = keystoreParam.substring(separatorPos + 1).trim();
					}
				}
			}
			catch (final Exception e) {
				LOGGER.warning(
					"Se ha intentado cargar un almacen de certificados no soportado, se cargara el por defecto: " + e //$NON-NLS-1$
				);
			}
		}

		MiniAfirmaApplet.configureLookAndFeel();

		// Google Analytics
		final AnalyticsConfigData config = new AnalyticsConfigData(GOOGLE_ANALYTICS_TRACKING_CODE);
		final JGoogleAnalyticsTracker tracker = new JGoogleAnalyticsTracker(config, GoogleAnalyticsVersion.V_4_7_2);
		tracker.trackPageView(
			getCodeBase().toString(),
			"MiniApplet Cliente @firma " + getVersion(), //$NON-NLS-1$
			getCodeBase().getHost().toString()
		);

		LOGGER.info("Miniapplet Afirma " + getVersion()); //$NON-NLS-1$

		LOGGER.info("Sistema operativo: " + System.getProperty("os.name")); //$NON-NLS-1$ //$NON-NLS-2$
		LOGGER.info("Version del SO: " + System.getProperty("os.version")); //$NON-NLS-1$ //$NON-NLS-2$
		LOGGER.info("Version de Java: " + System.getProperty("java.version")); //$NON-NLS-1$ //$NON-NLS-2$
		LOGGER.info("Arquitectura del JRE: " + Platform.getJavaArch()); //$NON-NLS-1$
		LOGGER.info("Java Vendor: " + System.getProperty("java.vm.vendor")); //$NON-NLS-1$ //$NON-NLS-2$

		LOGGER.info("Localizacion por defecto: " + Locale.getDefault()); //$NON-NLS-1$
	}

	/** {@inheritDoc} */
	@Override
	public void start() {
		super.start();

		try {
			AccessController.doPrivileged(new PrivilegedExceptionAction<Void>() {
				@Override
				public Void run() throws Exception {
					JarSignatureCertExtractor.insertJarSignerOnCACerts(this);
					return null;
				}
			});

		} catch (final Exception e) {
			LOGGER.warning(
					"No se ha podido insertar la cadena de confianza del certificado de firma del applet en el almacen de confianza de Java: " + e); //$NON-NLS-1$
		}
	}

	/** {@inheritDoc} */
	@Override
	public String getErrorMessage() {
		return this.errorMessage;
	}

	/** {@inheritDoc} */
	@Override
	public String getErrorType() {
		return this.errorType;
	}

	/** Establece el error en base a la excepción recibida.
	 * @param e Excepción que produjo el error. */
	private void setError(final Throwable e) {
		setError(e, null);
	}

	/** Establece el mensaje de error recibido y el tipo de error en base a la excepción.
	 * Si no se indica un mensaje este también se toma de la excepción.
	 * @param e Excepción que produjo el error.
	 * @param message Mensaje descriptivo del error. */
	private void setError(final Throwable e, final String message) {
		Throwable ex = e;
		if (e instanceof PrivilegedActionException && e.getCause() != null) {
			ex = e.getCause();
		}

		this.errorMessage = message != null ? message :
			ex.getLocalizedMessage() != null ? ex.getLocalizedMessage() :
			ex.getMessage() != null ? ex.getMessage() :
				ex.toString();

		this.errorType = ex.getClass().getCanonicalName();

		// Mostramos la traza de error a traves del log
		final ByteArrayOutputStream baos = new ByteArrayOutputStream();
		final PrintWriter writer = new PrintWriter(baos);
		e.printStackTrace(writer);
		writer.flush();
		writer.close();

		LOGGER.severe(new String(baos.toByteArray()));
	}

	/** Elimina el tipo y mensaje de error establecido previamente. */
	private void clearError() {
		this.errorType = null;
		this.errorMessage = null;
	}

	/** Permite que el usuario seleccione un certificado del almacén configurado, o
	 * el por defecto si no se indicó, y devuelve su clave privada.
	 * @param params Configuración general establecida para la operación.
	 * @return Clave privada asociada al certificado seleccionado.
	 * @throws PrivilegedActionException Cuando ocurre un error de seguridad.
	 * @throws AOCancelledOperationException Cuando se cancela la operación. */
	private PrivateKeyEntry selectPrivateKey(final Properties params) throws PrivilegedActionException {
		if (this.stickySignatory && this.stickyKeyEntry != null) {
			return this.stickyKeyEntry;
		}
		final SelectPrivateKeyAction selectPrivateKeyAction;
		if (this.keystoreType == null) {
			selectPrivateKeyAction = new SelectPrivateKeyAction(
					Platform.getOS(),
					Platform.getBrowser(this.userAgent),
					new CertFilterManager(params),
					this);
		}
		else {
			selectPrivateKeyAction = new SelectPrivateKeyAction(
					this.keystoreType,
					this.keystoreLib,
					new CertFilterManager(params),
					this);
		}
		final PrivateKeyEntry keyEntry = AccessController.doPrivileged(selectPrivateKeyAction);
		if (this.stickySignatory) {
			this.stickyKeyEntry = keyEntry;
		}
		return keyEntry;
	}

	/** Devuelve un manejador de firma compatible con un formato de firma o, de no establecerse, con
	 * una firma electrónica concreta.
	 * @param format Formato de firma.
	 * @param sign Firma electrónica.
	 * @return Manejador de firma.
	 * @throws AOFormatFileException Cuando el formato o la firma no estan soportados.
	 * @throws PrivilegedActionException Cuando ocurre un error de seguridad.
	 * @throws IOException Cuando se produce un error durante la lectura de los datos.
	 * @throws NullPointerException Cuando no se indica ni formato ni firma como paránmetro.
	 */
	private static AOSigner selectSigner(final String format,
			                             final byte[] sign) throws AOFormatFileException,
			                                                       PrivilegedActionException, IOException {
		final AOSigner signer;
		if (format != null && !SIGNATURE_FORMAT_AUTO.equalsIgnoreCase(format)) {
			signer = MiniAfirmaApplet.getSigner(format);
			if (signer == null) {
				throw new AOFormatFileException("No esta soportado el formato de firma: " + format); //$NON-NLS-1$
			}
		}
		else if (sign != null) {
			signer = MiniAfirmaApplet.getSigner(sign);
			if (signer == null) {
				throw new IllegalArgumentException(
					"Los datos introducidos no se corresponden con una firma soportada" //$NON-NLS-1$
				);
			}
		}
		else {
			// Si llegamos aqui es por no haberse indicado el formato de firma y que no disponemos de
			// una firma del que tomarlo (por lo que no puede ser una multifirma)
			throw new IllegalArgumentException(
				"No se ha indicado el formato para la operacion de firma" //$NON-NLS-1$
			);
		}
		return signer;
	}

	/** Recupera un manejador de firma compatible con el formato indicado. Si no se encuentra uno
	 * compatible, se devuelve {@code null}.
	 * @param format Nombre de un formato de firma.
	 * @return Manejador de firma.
	 * @throws PrivilegedActionException Cuando ocurre un problema de seguridad.
	 */
	private static AOSigner getSigner(final String format) throws PrivilegedActionException {
		return AccessController.doPrivileged(new SelectSignerAction(format));
	}

	/** Recupera un manejador de firma compatible con la firma indicada. Si no se encuentra uno
	 * compatible, se devuelve {@code null}.
	 * @param signature Firma electrónica.
	 * @return Manejador de firma.
	 * @throws PrivilegedActionException Cuando ocurre un problema de seguridad.
	 */
	private static AOSigner getSigner(final byte[] signature) throws PrivilegedActionException {
		return AccessController.doPrivileged(new SelectSignerAction(signature));
	}

	/** Configura la apariencia de los diálogos Java siguiendo la configuración
	 * establecida en el sistema.
	 */
	private static void configureLookAndFeel() {
		try {
			UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());
		}
		catch (final Exception e) {
			LOGGER.warning("No se ha podido establecer el Look&Feel: " + e); //$NON-NLS-1$
		}

		// Nos aseguramos de que los dialogos salgan decorados
		javax.swing.JDialog.setDefaultLookAndFeelDecorated(true);
		javax.swing.JFrame.setDefaultLookAndFeelDecorated(true);
	}

	/** Limpia los parámetros recibidos en las funciones del applet sustituyendo
	 * cadenas vacías por nulos y eliminando los espacios en blanco al principio
	 * y final de las cadenas
	 * @param appletParam Parámetro que se desea limpiar.
	 * @return Parámetro preparado para su uso. */
	private static String cleanParam(final String appletParam) {
		return appletParam == null || appletParam.trim().length() < 1 ?
				null : appletParam.trim();
	}

	/**
	 * En caso de indicarse una expresión clave como juego de caracteres, se calcula el
	 * juego de caracteres en base al algoritmo determinado para esa expresión. Si no
	 * es una expresión reconocida se devuelve la propia entrada. Las expresiones
	 * permitidas son:
	 * <ul>
	 *   <li><b>auto</b>: Devuelve el juego de caracteres detectado en el texto proporcionado.
	 *   Si no puede detectarse, se devolverá el juego de caracteres del sistema.</li>
	 *   <li><b>default</b>: Devuelve el juego de caracteres por defecto del sistema.</li>
	 * </ul>
	 * @param charset Expresión clave o juego de caracteres.
	 * @param textBase64 Texto auxiliar para determinar el juego de caracteres.
	 * @return Juego de caracteres introducido u obtenido a partir de la expresión
	 * clave.
	 */
	private static String getCharset(final String charset, final String textBase64) {
		if ("auto".equalsIgnoreCase(charset)) { //$NON-NLS-1$
			if (textBase64 == null) {
				LOGGER.warning(
					"No se puede detectar el juego de caracteres de un texto nulo, se devolvera la codificacion por defecto" //$NON-NLS-1$
				);
				return getCharset("default", null); //$NON-NLS-1$
			}
			final byte[] text;
			try {
				text = Base64.decode(textBase64);
			}
			catch (final IOException e) {
				LOGGER.warning("Los datos proporcionados est\u00E1n mal codificados en base 64"); //$NON-NLS-1$
				return getCharset("default", null); //$NON-NLS-1$
			}
			final UniversalDetector detector = new UniversalDetector();
			detector.handleData(text, 0, text.length);
			detector.dataEnd();
			if (detector.isDone()) {
				final String detectedCharset = detector.getDetectedCharset();
				if (detectedCharset != null) {
					return detectedCharset;
				}
			}
			// Si no se ha podido detectar, devolvemos la codificacion por defecto
			LOGGER.warning(
					"No se ha podido autodetectar el juego de caracteres, se devolvera el por defecto del sistema" //$NON-NLS-1$
			);
			return getCharset("default", null); //$NON-NLS-1$
		}
		else if ("default".equalsIgnoreCase(charset) || charset == null) { //$NON-NLS-1$
			return AccessController.doPrivileged(new GetPropertyAction("file.encoding")); //$NON-NLS-1$
		}
		return charset;
	}

	/** Imprime en el logger el texto "MiniApplet cargado y en ejecución". El uso de
	 * este método permite determinar si el applet se encuentra inicializado. */
	@Override
	public String echo() {
		final String javaInfo =
				"Java vendor: " + System.getProperty("java.vm.vendor") + '\n' + //$NON-NLS-1$ //$NON-NLS-2$
				"Java version: " + System.getProperty("java.version") + '\n' + //$NON-NLS-1$ //$NON-NLS-2$
				"Java architecture: " + Platform.getJavaArch(); //$NON-NLS-1$

		LOGGER.info("MiniApplet cargado y en ejecuci\u00F3n"); //$NON-NLS-1$
		LOGGER.info(javaInfo);

		return javaInfo;
	}

	private byte[] readChunk() throws IOException {
		if (this.chunkedReturnStream == null) {
			return new byte[0];
		}

		final byte[] buf;
		boolean finished = false;
		final int available = this.chunkedReturnStream.available();
		if (available > BUFFER_SIZE) {
			buf = new byte[BUFFER_SIZE];
		}
		else if (available > 0){
			buf = new byte[available];
			finished = true;
		}
		else {
			this.chunkedReturnStream = null;
			return new byte[0];
		}
		final int readed = this.chunkedReturnStream.read(buf);
		if (readed != buf.length) {
			this.chunkedReturnStream = null;
			throw new IOException("Lectura incompleta de la porcion de datos resultantes"); //$NON-NLS-1$
		}

		if (finished) {
			this.chunkedReturnStream.close();
			this.chunkedReturnStream = null;
		}

		return buf;
	}

	private String chunkReturn(final String completeReturn) throws IOException {
		if (completeReturn == null || completeReturn.length() <= BUFFER_SIZE) {
			return completeReturn;
		}
		LOGGER.info(
			"El resultado es demasiado grande (" + //$NON-NLS-1$
			completeReturn.length() +
			" caracteres), se ha devuelto un resultado parcial y debe solicitarse el resto en llamadas adicionales" //$NON-NLS-1$
		);
		this.chunkedReturnStream = new ByteArrayInputStream(completeReturn.getBytes(DEFAULT_CHUNK_ENCODING));
		return new String(readChunk(), DEFAULT_CHUNK_ENCODING);
	}

	@Override
	public String getRemainingData() throws IOException {
		final byte[] chunk = readChunk();
		if (chunk == null) {
			throw new IOException("Se ha producido una lectura parcial nula"); //$NON-NLS-1$
		}
		if (chunk.length == 0) {
			LOGGER.info("Se ha terminado de devolver un resultado grande"); //$NON-NLS-1$
			return EOF;
		}
		LOGGER.info("Devolucion parcial de " + chunk.length + " caracteres"); //$NON-NLS-1$ //$NON-NLS-2$
		return new String(chunk, DEFAULT_CHUNK_ENCODING);
	}

	@Override
	public void addData(final String data) {
		if (data == null) {
			this.dataStore.setLength(0);
		}
		else {
			this.dataStore.append(data);
			LOGGER.info("Anadida porcion de datos de longitud: " + data.length()); //$NON-NLS-1$
		}
	}

	/** Recupera el identificador del numero de version del MiniApplet a partir de su Manifest.
	 * @return Identificador de la versión. */
	private static String getVersion() {
		try {
			final InputStream manifestIs = MiniAfirmaApplet.class.getClassLoader().getResourceAsStream("META-INF/MANIFEST.MF"); //$NON-NLS-1$
			final Properties metadata = new Properties();
			metadata.load(manifestIs);
			manifestIs.close();

			return metadata.getProperty("Specification-Version", ""); //$NON-NLS-1$ //$NON-NLS-2$
		}
		catch (final Exception e) {
			LOGGER.warning("No se ha podido identificar el numero de version del MiniApplet a partir del Manifest: " + e); //$NON-NLS-1$
			return ""; //$NON-NLS-1$
		}
	}

	/**
	 * Establece las propiedades del sistema indicadas como argumentos y separadas por '-D'.
	 * Las propiedades deben establecerse como clave=valor.
	 * @param systemProperties Texto con las propiedades que establecer.
	 */
	private static void setSystemProperties(final String systemProperties) {

		LOGGER.info("setSystemProperties: " + systemProperties); //$NON-NLS-1$

		if (systemProperties != null && systemProperties.trim().length() > 0) {
			final String[] properties = systemProperties.split("-D");  //$NON-NLS-1$
			for (final String property : properties) {
				final int equalIndex = property.indexOf('=');
				if (equalIndex != -1) {
					LOGGER.info("Establecemos la propiedad del sistema: " + property.trim()); //$NON-NLS-1$
					System.setProperty(property.substring(0, equalIndex).trim(), property.substring(equalIndex + 1).trim());
				}
			}
		}
	}

	/** Establece la localización por defecto de la aplicación.
	 * @param locale Código ISO del idioma a establecer. */
	private static void setLocale(final String locale) {

		LOGGER.info("setLocale: " + locale); //$NON-NLS-1$

		if (locale == null || locale.trim().length() == 0) {
			return;
		}

		final String[] localeComponents = locale.replace('-', '_').split("_"); //$NON-NLS-1$
		if (localeComponents.length == 1) {
			Locale.setDefault(new Locale(localeComponents[0]));
		}
		else if (localeComponents.length == 2) {
			Locale.setDefault(new Locale(localeComponents[0], localeComponents[1]));
		}
		else if (localeComponents.length > 2) {
			Locale.setDefault(new Locale(localeComponents[0], localeComponents[1], localeComponents[2]));
		}
	}

	@Override
	public String getCurrentLog() {
		return AccessController.doPrivileged(new GetCurrentLogAction());
	}

	/**
	 * Este metodo sirve para identificar cuando se ha configurado una firma con el formato XAdES
	 * de tipo enveloped y la propiedad {@code mode} con el valor {@code explicit}. Este tipo de firma
	 * no existe.
	 * @param format Formato declarado para la firma.
	 * @param config Parámetros adicionales declarados para la firma.
	 * @return {@code true} si se configura una firma XAdES Enveloped explicit, {@code false} en caso contrario.
	 * @deprecated Uso temporal hasta que se elimine el soporte de firmas XAdES explicitas.
	 */
	@Deprecated
	private static boolean isXadesEnvelopedExplicit(final String format, final Properties config) {
		return isXadesExplicitConfigurated(format, config) &&
				AOSignConstants.SIGN_FORMAT_XADES_ENVELOPED.equalsIgnoreCase(config.getProperty("format")) //$NON-NLS-1$
			;
	}

	/**
	 * Este metodo sirve para identificar cuando se ha configurado una firma con el formato XAdES
	 * y la propiedad {@code mode} con el valor {@code explicit}. Esta no es una firma correcta,
	 * pero por compatibilidad con los tipos de firmas del applet pesado se ha incluido aquí.
	 * @param format Formato declarado para la firma.
	 * @param config Parámetros adicionales declarados para la firma.
	 * @return {@code true} si se configura una firma XAdES explicit, {@code false} en caso contrario.
	 * @deprecated Uso temporal hasta que se elimine el soporte de firmas XAdES explicitas.
	 */
	@Deprecated
	private static boolean isXadesExplicitConfigurated(final String format, final Properties config) {
		return format != null && format.toLowerCase().startsWith("xades") && config != null && //$NON-NLS-1$
				AOSignConstants.SIGN_MODE_EXPLICIT.equalsIgnoreCase(config.getProperty("mode")) //$NON-NLS-1$
			;
	}
}


text:
namespace System.Runtime.InteropServices.WindowsRuntime
{
    /// <summary>
    /// A managed wrapper of IReferenceArray<T>
    /// </summary>
    [System.Runtime.CompilerServices.DependencyReductionRootAttribute]
    [McgInternalTypeAttribute]
    public sealed class ReferenceArrayImpl<T> : ReferenceArrayImplBase, IReferenceArray<T>
    {
        private T[] _value;

        public ReferenceArrayImpl(T[] obj, PropertyType type) : base(obj, type)
        {
            _value = obj;
            m_unboxed = true;
        }

        public T[] get_Value()
        {
            if (!m_unboxed)
            {
                _value = (T[])m_data;
                m_unboxed = true;
            }

            return _value;
        }
    }
}


text:
module Azure::Resources::Mgmt::V2018_06_01
  module Models
    #
    # Defines values for ApplicationArtifactType
    #
    module ApplicationArtifactType
      Template = "Template"
      Custom = "Custom"
    end
  end
end