text:
#include "Precompiled.h"
#include "BoardPiecePlace.h"
#include "Board.h"

BoardPiecePlace* BoardPiecePlace::create ( Board* pBoard, KDuint uColumn, KDuint uRow, const CCSize& tSize )
{
	BoardPiecePlace*	pRet = new BoardPiecePlace ( );

	if ( pRet && pRet->initWithBoard ( pBoard, uColumn, uRow, tSize ) )
	{
		pRet->autorelease ( );
	}
	else
	{
		CC_SAFE_DELETE ( pRet );
	}

	return pRet;
}

KDbool BoardPiecePlace::initWithBoard ( Board* pBoard, KDuint uColumn, KDuint uRow, const CCSize& tSize )
{
	if ( !CCNode::init ( ) )
	{
		return KD_FALSE;
	}

	m_uColumn		= uColumn;
	m_uRow			= uRow;
	m_pBoard		= pBoard;
	m_pCurrentPiece	= KD_NULL;
	m_eState		= EMPTY;
	m_tRect			= CCRect ( -tSize.cx / 2, -tSize.cy / 2, tSize.cx, tSize.cy );

	return KD_TRUE;
}

// Dummy method for CCRGBAProtocol protocol.
KDvoid BoardPiecePlace::setColor ( const ccColor3B& tColor )
{

}

// Dummy method for CCRGBAProtocol protocol
const ccColor3B& BoardPiecePlace::getColor ( KDvoid )
{
	return ccWHITE;
}

const ccColor3B& BoardPiecePlace::getDisplayedColor ( KDvoid )
{
	return ccWHITE;
}

GLubyte BoardPiecePlace::getDisplayedOpacity ( KDvoid )
{
	return 255;
}

// Dummy method for CCRGBAProtocol protocol.
GLubyte BoardPiecePlace::getOpacity ( KDvoid )
{
	return 255;
}

KDvoid BoardPiecePlace::setOpacity ( GLubyte cOpacity )
{
	switch ( m_eState )
	{
		case EMPTY :
			break;

		case UNSELECTED_PIECE :
			( (CCSprite*) this->getChildByTag ( PIECE_SPRITE_TAG ) )->setOpacity ( cOpacity );
			break;

		case SELECTED_PIECE :
			( (CCSprite*) this->getChildByTag ( PIECE_SPRITE_TAG ) )->setOpacity ( cOpacity );
			( (CCSprite*) this->getChildByTag ( SELECTION_SPRITE_TAG ) )->setOpacity ( cOpacity );
			break;

		case ENDING_CORRECT_MATCHING :
			( (CCSprite*) this->getChildByTag ( MATCHING_SPRITE_TAG ) )->setOpacity ( cOpacity );
			break;

		case STARTING_CORRECT_MATCHING :
			( (CCSprite*) this->getChildByTag ( PIECE_SPRITE_TAG ) )->setOpacity ( cOpacity );
			( (CCSprite*) this->getChildByTag ( MATCHING_SPRITE_TAG ) )->setOpacity ( cOpacity );
			break;

		case INCORRECT_MATCHING :
			( (CCSprite*) this->getChildByTag ( PIECE_SPRITE_TAG ) )->setOpacity ( cOpacity );
			( (CCSprite*) this->getChildByTag ( MATCHING_SPRITE_TAG ) )->setOpacity ( cOpacity );
			break;

		default :
			CCAssert ( KD_FALSE, "Unknown BoardPiecePlace state in setOpacity." );
	}
}

KDvoid BoardPiecePlace::setOpacityModifyRGB ( KDbool bValue )
{

}

KDbool BoardPiecePlace::isOpacityModifyRGB ( KDvoid )
{
	return KD_FALSE;
}

KDbool BoardPiecePlace::isCascadeColorEnabled ( KDvoid )
{
	return KD_FALSE;
}

KDvoid BoardPiecePlace::setCascadeColorEnabled ( KDbool bCascadeColorEnabled )
{

}

KDvoid BoardPiecePlace::updateDisplayedColor ( const ccColor3B& tColor )
{

}

KDbool BoardPiecePlace::isCascadeOpacityEnabled ( KDvoid )
{
	return KD_FALSE;
}

KDvoid BoardPiecePlace::setCascadeOpacityEnabled ( KDbool bCascadeOpacityEnabled )
{

}

KDvoid BoardPiecePlace::updateDisplayedOpacity ( GLubyte cOpacity )
{

}

KDbool BoardPiecePlace::containsTouchLocation ( CCTouch* pTouch )
{
	return m_tRect.containsPoint ( this->convertTouchToNodeSpaceAR ( pTouch ) );
}

// A BoardPiecePlace may have or may not have a Piece. This Piece maybe is being killed, in this case is not selectable.
// Also, if there is no Piece, obviously is not selectable.
KDbool BoardPiecePlace::isPieceSelectable ( KDvoid )
{
	return m_eState == UNSELECTED_PIECE;
}

KDbool BoardPiecePlace::processTouch ( CCTouch* pTouch )
{
	// is game state in playing mode and board state in waiting for input state?
	if ( this->containsTouchLocation ( pTouch ) && m_pBoard->canBoardPiecePlaceBeSelected ( ) &&
	   ( m_eState == UNSELECTED_PIECE || m_eState == SELECTED_PIECE ) )
	{
		m_pBoard->boardPiecePlaceWasSelected ( this );
		return KD_TRUE;
	}

	return KD_FALSE;
}

// Sets currentPiece and change state to UNSELECTED.
// Precondition: state must be EMPTY.
// Call reset in order to change to EMPTY state.
KDvoid BoardPiecePlace::setPiece ( Piece* pPiece )
{
	CCAssert ( m_eState == EMPTY, "m_eState must be EMPTY in setPiece.");
	m_pCurrentPiece = pPiece;
	this->changeBoardPiecePlaceState ( UNSELECTED_PIECE );
}

Piece* BoardPiecePlace::getCurrentPiece ( KDvoid )
{
	return m_pCurrentPiece;
}

// Removes Piece if used and selection or matching animation.
// Change state to EMPTY.
KDvoid BoardPiecePlace::reset ( KDvoid )
{
	m_eState = EMPTY;
	m_pCurrentPiece = KD_NULL;
	this->removeAllChildrenWithCleanup ( KD_TRUE );
}

KDvoid BoardPiecePlace::select ( KDvoid )
{
	CCAssert ( m_eState == UNSELECTED_PIECE, "m_eState must be UNSELECTED_PIECE in select." );
	this->changeBoardPiecePlaceState ( SELECTED_PIECE );
}

KDvoid BoardPiecePlace::unselect ( KDvoid )
{
	CCAssert ( m_eState == SELECTED_PIECE, "m_eState must be SELECTED_PIECE in unselect." );
	this->changeBoardPiecePlaceState ( UNSELECTED_PIECE );
}

// Called by Board to start a correct matching sequence.
KDvoid BoardPiecePlace::correctMatching ( KDvoid )
{
	CCAssert ( ( m_eState == SELECTED_PIECE || m_eState == UNSELECTED_PIECE ), "m_eState must be SELECTED_PIECE or UNSELECTED_PIECE in correctMatching." );
	this->changeBoardPiecePlaceState ( STARTING_CORRECT_MATCHING );
}

// Called by Board.
KDvoid BoardPiecePlace::incorrectMatching ( KDvoid )
{
	CCAssert ( ( m_eState == SELECTED_PIECE || m_eState == UNSELECTED_PIECE ), "m_eState must be SELECTED_PIECE or UNSELECTED_PIECE in incorrectMatching." );
	this->changeBoardPiecePlaceState ( INCORRECT_MATCHING );
}

// Called in the middle of a correct matching sequence.
// Used to play correct matching sound and remove piece sprite.
KDvoid BoardPiecePlace::correctMatchingWillBeDoneCallback ( CCNode* pSender )
{
	this->changeBoardPiecePlaceState ( ENDING_CORRECT_MATCHING );
}

// Called after correct matching sequence was done. Used to change object's state.
KDvoid BoardPiecePlace::correctMatchingWasDoneCallback ( CCNode* pSender )
{
	this->changeBoardPiecePlaceState ( EMPTY );
}

// Called after incorrect matching sequence was done. Used to change object's state.
KDvoid BoardPiecePlace::incorrectMatchingWasDoneCallback ( CCNode* pSender )
{
	this->changeBoardPiecePlaceState ( UNSELECTED_PIECE );
}

KDvoid BoardPiecePlace::onEnterBoardPiecePlaceState ( BoardPiecePlaceState eState )
{
	if ( eState == EMPTY )
	{

	}
	else if ( eState == UNSELECTED_PIECE )
	{

	}
	else if ( eState == SELECTED_PIECE )
	{
		// add a sprite for selection and its animation
		CCSprite*	pSelectedSprite = CCSprite::createWithTexture ( m_pBoard->getSelectedTexture ( ) );
		pSelectedSprite->setTag ( SELECTION_SPRITE_TAG );
		this->addChild ( pSelectedSprite );

		CCRepeatForever*	pSelectedAction = (CCRepeatForever*) m_pBoard->getSelectedAction ( )->copy ( )->autorelease ( );
		pSelectedSprite->runAction ( pSelectedAction );
	}
	else if ( eState == STARTING_CORRECT_MATCHING )
	{

		// add sprite where matching sequence will be executed
		CCSprite*	pStartingMatchingSprite = CCSprite::createWithTexture ( m_pBoard->getStartingMatchingTexture ( ) );
		pStartingMatchingSprite->setTag ( MATCHING_SPRITE_TAG );
		this->addChild ( pStartingMatchingSprite );

		// create sequence action
		CCAnimate*	pStartingMatchingAction = (CCAnimate*) m_pBoard->getStartingMatchingAction ( )->copy ( )->autorelease ( );
		CCAnimate*	pCorrectMatchingEndingAction = (CCAnimate*) m_pBoard->getCorrectMatchingEndingAction ( )->copy ( )->autorelease ( );

		CCAction*	pAction = CCSequence::create
		(
			pStartingMatchingAction,
			CCCallFuncN::create ( this, callfuncN_selector ( BoardPiecePlace::correctMatchingWillBeDoneCallback ) ),
			pCorrectMatchingEndingAction,
			CCCallFuncN::create ( this, callfuncN_selector ( BoardPiecePlace::correctMatchingWasDoneCallback ) ),
			KD_NULL
		);

		// run action
		pStartingMatchingSprite->runAction ( pAction );
	}
	else if ( eState == ENDING_CORRECT_MATCHING )
	{

	}
	else if ( eState == INCORRECT_MATCHING )
	{
		// add sprite where matching sequence will be executed
		CCSprite*	pStartingMatchingSprite = CCSprite::createWithTexture ( m_pBoard->getStartingMatchingTexture ( ) );
		pStartingMatchingSprite->setTag ( MATCHING_SPRITE_TAG );
		this->addChild ( pStartingMatchingSprite );
		m_pBoard->reorderChild ( this, 1 );

		// create sequence action
		CCAnimate*	pStartingMatchingAction = (CCAnimate*) m_pBoard->getStartingMatchingAction ( )->copy ( )->autorelease ( );
		CCAnimate*	pIncorrectMatchingEndingAction = (CCAnimate*) m_pBoard->getIncorrectMatchingEndingAction ( )->copy ( )->autorelease ( );

		CCAction*	pAction = CCSequence::create
		(
			pStartingMatchingAction,
			pIncorrectMatchingEndingAction,
			CCCallFuncN::create ( this, callfuncN_selector ( BoardPiecePlace::incorrectMatchingWasDoneCallback ) ),
			KD_NULL
		);

		// run action
		pStartingMatchingSprite->runAction ( pAction );
	}
}

KDvoid BoardPiecePlace::onExitBoardPiecePlaceState ( BoardPiecePlaceState eState )
{
	if ( eState == EMPTY )
	{
		CCSpriteFrame*	pPieceSpriteFrame = m_pCurrentPiece->getSpriteFrame ( );
		CCSprite*		pSprite = CCSprite::createWithSpriteFrame ( pPieceSpriteFrame );
		pSprite->setTag ( PIECE_SPRITE_TAG );
		this->addChild ( pSprite );
	}
	else if ( eState == UNSELECTED_PIECE )
	{

	}
	else if ( eState == SELECTED_PIECE )
	{
		this->removeChildByTag ( SELECTION_SPRITE_TAG, KD_TRUE );
	}
	else if ( eState == STARTING_CORRECT_MATCHING )
	{
		this->removeChildByTag ( PIECE_SPRITE_TAG, KD_TRUE );
	}
	else if ( eState == ENDING_CORRECT_MATCHING )
	{
		this->removeChildByTag ( MATCHING_SPRITE_TAG, KD_TRUE );
	}
	else if ( eState == INCORRECT_MATCHING )
	{
		m_pBoard->reorderChild ( this, 1 );
		this->removeChildByTag ( MATCHING_SPRITE_TAG, KD_TRUE );
	}
}

KDvoid BoardPiecePlace::changeBoardPiecePlaceState ( BoardPiecePlaceState eState )
{
	this->onExitBoardPiecePlaceState ( m_eState );

	if ( m_eState == EMPTY && eState == UNSELECTED_PIECE )
	{

	}
	else if ( m_eState == UNSELECTED_PIECE && eState == SELECTED_PIECE )
	{

	}
	else if ( m_eState == SELECTED_PIECE && eState == UNSELECTED_PIECE )
	{

	}
	else if ( m_eState == SELECTED_PIECE && eState == STARTING_CORRECT_MATCHING )
	{

	}
	else if ( m_eState == STARTING_CORRECT_MATCHING && eState == ENDING_CORRECT_MATCHING )
	{

	}
	else if ( m_eState == ENDING_CORRECT_MATCHING && eState == EMPTY )
	{

	}
	else if ( m_eState == SELECTED_PIECE && eState == INCORRECT_MATCHING )
	{

	}
	else if ( m_eState == INCORRECT_MATCHING && eState == UNSELECTED_PIECE )
	{

	}
	else if ( m_eState == UNSELECTED_PIECE && eState == STARTING_CORRECT_MATCHING )
	{

	}
	else if ( m_eState == UNSELECTED_PIECE && eState == INCORRECT_MATCHING )
	{

	}
	else
	{
		CCAssert ( KD_FALSE, "Unknown transition." );
	}

	m_eState = eState;

	this->onEnterBoardPiecePlaceState ( eState );
}

redpajama_set_name: RedPajamaGithub


text:
<?php

/* SonataAdminBundle:CRUD:show_array.html.twig */
class __TwigTemplate_d917e6e4eaa80de2dd3c6f2845ec5d40bd859b83feb64985978e83c0ace32cd8 extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        $this->parent = $this->env->loadTemplate("SonataAdminBundle:CRUD:base_show_field.html.twig");

        $this->blocks = array(
            'field' => array($this, 'block_field'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "SonataAdminBundle:CRUD:base_show_field.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 14
    public function block_field($context, array $blocks = array())
    {
        // line 15
        echo "    ";
        $context['_parent'] = (array) $context;
        $context['_seq'] = twig_ensure_traversable($this->getContext($context, "value"));
        foreach ($context['_seq'] as $context["key"] => $context["val"]) {
            // line 16
            echo "        ";
            if ($this->getAttribute($this->getAttribute($this->getContext($context, "field_description"), "options", array()), "safe", array())) {
                // line 17
                echo "            [";
                echo twig_escape_filter($this->env, $context["key"], "html", null, true);
                echo " => ";
                echo $context["val"];
                echo "]
        ";
            } else {
                // line 19
                echo "            [";
                echo twig_escape_filter($this->env, $context["key"], "html", null, true);
                echo " => ";
                echo twig_escape_filter($this->env, $context["val"], "html", null, true);
                echo "]
        ";
            }
            // line 21
            echo "    ";
        }
        $_parent = $context['_parent'];
        unset($context['_seq'], $context['_iterated'], $context['key'], $context['val'], $context['_parent'], $context['loop']);
        $context = array_intersect_key($context, $_parent) + $_parent;
    }

    public function getTemplateName()
    {
        return "SonataAdminBundle:CRUD:show_array.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  55 => 21,  47 => 19,  39 => 17,  36 => 16,  31 => 15,  28 => 14,);
    }
}


text:
package net.shibboleth.idp.cas.flow;

import net.shibboleth.idp.cas.protocol.ProtocolError;
import net.shibboleth.idp.cas.ticket.TicketContext;
import net.shibboleth.idp.profile.AbstractProfileAction;
import net.shibboleth.idp.session.IdPSession;
import net.shibboleth.idp.session.SessionException;
import net.shibboleth.idp.session.SessionResolver;
import net.shibboleth.idp.session.context.SessionContext;
import net.shibboleth.idp.session.criterion.SessionIdCriterion;
import net.shibboleth.utilities.java.support.logic.Constraint;
import net.shibboleth.utilities.java.support.resolver.CriteriaSet;
import net.shibboleth.utilities.java.support.resolver.ResolverException;
import org.opensaml.profile.context.ProfileRequestContext;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.webflow.execution.Event;
import org.springframework.webflow.execution.RequestContext;

import javax.annotation.Nonnull;

/**
 * IdP session validation for back-channel ticket request and validation. Possible outcomes:
 *

 *
{@link ProtocolError#SessionExpired sessionExpired}

 *
{@link ProtocolError#SessionRetrievalError sessionRetrievalError}

 *
{@link Events#Success success}

 *

 *

 * Requires a {@link net.shibboleth.idp.cas.ticket.TicketContext} bound to the
 * {@link org.opensaml.profile.context.ProfileRequestContext} that is provided to the action.
 *

 * On success, adds the current {@link net.shibboleth.idp.session.IdPSession}
 * as request scope parameter under the key {@value FlowStateSupport#IDP_SESSION_KEY} and also to a
 * {@link net.shibboleth.idp.session.context.SessionContext} that is a subcontext of the input
 * {@link org.opensaml.profile.context.ProfileRequestContext}.
 *
 * @author Marvin S. Addison
 */
public class ValidateIdpSessionAction extends AbstractProfileAction {

    /** Class logger. */
    private final Logger log = LoggerFactory.getLogger(ValidateIdpSessionAction.class);

    /** Looks up IdP sessions. */
    @Nonnull private final SessionResolver sessionResolver;

    /**
     * Creates a new instance.
     * @param resolver IdP session resolver component.
     */
    public ValidateIdpSessionAction(@Nonnull SessionResolver resolver) {
        this.sessionResolver = Constraint.isNotNull(resolver, "Session resolver cannot be null.");
    }

    @Nonnull
    @Override
    protected Event doExecute(
            final @Nonnull RequestContext springRequestContext,
            final @Nonnull ProfileRequestContext profileRequestContext) {

        final TicketContext ticketContext = profileRequestContext.getSubcontext(TicketContext.class);
        if (ticketContext == null) {
            log.info("TicketContext not found in context tree.");
            return ProtocolError.IllegalState.event(this);
        }
        final String sessionId = ticketContext.getTicket().getSessionId();
        final IdPSession session;
        try {
            log.debug("Attempting to retrieve session {}", sessionId);
            session = sessionResolver.resolveSingle(new CriteriaSet(new SessionIdCriterion(sessionId)));
        } catch (ResolverException e) {
            log.debug("IdP session retrieval failed with error: {}", e);
            return ProtocolError.SessionRetrievalError.event(this);
        }
        boolean expired = (session == null);
        if (session != null) {
            try {
                expired = !session.checkTimeout();
                log.debug("Session {} expired={}", sessionId, expired);
            } catch (SessionException e) {
                log.debug("Error performing session timeout check. Assuming session has expired.", e);
                expired = true;
            }
        }
        if (expired) {
            return ProtocolError.SessionExpired.event(this);
        }
        FlowStateSupport.setIdpSession(springRequestContext, session);
        final SessionContext sessionContext = new SessionContext();
        sessionContext.setIdPSession(session);
        profileRequestContext.addSubcontext(sessionContext);
        return Events.Success.event(this);
    }
}


text:
/**
 * Created by Nikolay Chervyakov on 19.12.2014.
 */

/**
 * Controls Vulnerable elements
 */
can.Control('VulnBlock', {
    pluginName: 'vulnBlock',
    defaults: {
        link: null
    }
}, {
    init: function () {
        this.link = this.options.link;
        var $vulns = this.element.find('.vulnerability');

        if (!$vulns.length) {
            this.hide();
        } else {
            this.show();
        }
    },

    '{link} click': function (el, ev) {
        ev.preventDefault();
        this.toggleVisibility();
    },

    hide: function () {
        this.element.hide();
        this.link.text('Show vulnerabilities');
    },

    show: function () {
        this.element.show();
        this.link.text('Hide vulnerabilities');
    },

    toggleVisibility: function () {
        if (this.element.is(':visible')) {
            this.hide();
        } else {
            this.show();
        }
    }
});

/**
 * Controls Vulnerable elements
 */
can.Control('ConditionsBlock', {
    pluginName: 'conditionsBlock',
    defaults: {
        link: null
    }
}, {
    init: function () {
        this.link = this.options.link;
        var $conditions = this.element.find('.js-condition-row');

        if (!$conditions.length) {
            this.hide();
        } else {
            this.show();
        }
    },

    '{link} click': function (el, ev) {
        ev.preventDefault();
        this.toggleVisibility();
    },

    hide: function () {
        this.element.hide();
        this.link.text('Show conditions');
    },

    show: function () {
        this.element.show();
        this.link.text('Hide conditions');
    },

    toggleVisibility: function () {
        if (this.element.is(':visible')) {
            this.hide();
        } else {
            this.show();
        }
    }
});

/**
 * Controls Context
 */
var Context = can.Control('Context', {
    pluginName: 'contextControl'
}, {
    init: function () {
        this.fieldsBlock = this.element.find('> .panel-body > .context-fields');
        this.fieldsContainer = this.fieldsBlock.find('.js-fields-container');

        var fields = this.fieldsContainer.children('.js-field-block');
        this.fieldsIdCounter = fields.length;
        fields.contextField();
        this.fieldsContainer.sortable();
        //this.fieldsContainer.disableSelection();

        this.vulnBlock = this.element.find('> .panel-body > .js-vulns-block');
        this.vulnBlock.vulnBlock({link: this.element.find('> .panel-body > .js-show-vulns-link')});
        this.vulnBlock.children('.js-vulnerability-block').vulnerableElement();

        this.childrenContainer = this.element.find('> .panel-body > .js-child-contexts');
        var children = this.childrenContainer.children('.js-context-panel');
        this.childrenIdCounter = children.length;
        this.childrenContainer.sortable();
        //this.childrenContainer.disableSelection();

        this.hasParents = !!this.element.parents('.js-context-panel').length;

        if (!this.hasParents) {
            this.element.find('> .panel-heading .js-remove').remove();
            this.element.find('> .panel-heading .js-position-buttons').remove();
        }
        this.moveUpButton = this.element.find('> .panel-heading .js-move-up');
        this.moveDownButton = this.element.find('> .panel-heading .js-move-down');

        this.checkPositionButtons();
    },

    '> .panel-body > .context-fields .js-add-field click': function (el, ev) {
        ev.preventDefault();
        this.addField();
    },

    '> .panel-body > .context-fields .js-fields-container sortupdate': function () {
        this.calculateFieldOrder();
    },

    '> .panel-body > .js-child-contexts sortupdate': function () {
        this.checkChildrenPositionButtons();
    },

    '> .panel-body > .context-fields .js-field-block removefieldclaim': function (el) {
        el.remove();
        this.calculateFieldOrder();
    },

    '> .panel-heading .js-add-child-context click': function (el, ev) {
        ev.preventDefault();
        this.addContext();
    },

    '> .panel-heading .js-remove click': function (el, ev) {
        ev.preventDefault();
        this.element.remove();
    },

    '> .panel-heading .js-add-field click': function (el, ev) {
        ev.preventDefault();
        this.addField();
    },

    '> .panel-heading .js-move-up click': function (el, ev) {
        ev.preventDefault();
        var prevElement = this.element.prev('.js-context-panel');

        if (!prevElement.length) {
            return;
        }

        this.element.insertBefore(prevElement);
        this.checkPositionButtons();
        prevElement.contextControl('checkPositionButtons');
    },

    '> .panel-heading .js-move-down click': function (el, ev) {
        ev.preventDefault();
        var nextElement = this.element.next('.js-context-panel');

        if (!nextElement.length) {
            return;
        }

        this.element.insertAfter(nextElement);
        this.checkPositionButtons();
        nextElement.contextControl('checkPositionButtons');
    },

    addField: function () {
        var idBase = this.fieldsBlock.data('field-collection-id');
        var name = this.fieldsBlock.data('field-collection-name');
        var id = this.fieldsIdCounter++;
        var template = can.view("#tplField", {id: idBase + '_' + id, name: name + '[' + id + ']', field_index: id});
        this.fieldsContainer.append(template);
        var newFieldId = '#' + idBase + '_' + id;
        var newField = this.fieldsContainer.children(newFieldId);
        newField.contextField();
        newField.find('.js-name-field').focus();

        this.fieldsContainer.sortable();
        //this.fieldsContainer.disableSelection();

        this.calculateFieldOrder();
    },

    addContext: function () {
        var idBase = this.element.data('id') + '_children';
        var name = this.element.data('name') + '[children]';
        var id = this.childrenIdCounter++;
        var template = can.view("#tplContext", {id: idBase + '_' + id, name: name + '[' + id + ']', field_index: id});
        this.childrenContainer.append(template);
        var newContextId = '#' + idBase + '_' + id;
        var contextElement = this.childrenContainer.children(newContextId);
        contextElement.contextControl();
        location.hash = newContextId;
        contextElement.find('.js-name-field').focus();
        this.checkChildrenPositionButtons();
    },

    calculateFieldOrder: function () {
        var order = this.fieldsContainer.children('.js-field-block').map(function (i, f) { return $(f).data('id'); })
            .toArray().join(',');
        this.element.find('> .panel-body > .js-field-order').val(order);
    },

    checkPositionButtons: function () {
        if (!this.hasParents) {
            return;
        }

        if (this.element.prev('.js-context-panel').length) {
            this.moveUpButton.show();
        } else {
            this.moveUpButton.hide();
        }

        if (this.element.next('.js-context-panel').length) {
            this.moveDownButton.show();
        } else {
            this.moveDownButton.hide();
        }
    },

    checkChildrenPositionButtons: function () {
        this.childrenContainer.children('.js-context-panel').each(function () {
            var panel = $(this);
            panel.contextControl('checkPositionButtons')
        });
    }
});

/**
 * Controls Vulnerable elements
 */
can.Control('ContextField', {
    pluginName: 'contextField'
}, {
    init: function () {
        this.vulnBlock = this.element.find('.js-vulns-block');
        this.vulnBlock.vulnBlock({link: this.element.find('> .panel-body > .field-props .js-show-vulns-link')});
        this.vulnBlock.children('.js-vulnerability-block').vulnerableElement();
    },

    '> .panel-body > .field-props .js-remove-field click': function (el, ev) {
        ev.preventDefault();
        this.element.trigger('removefieldclaim');
    }
});

/**
 * Controls Vulnerable elements
 */
var VulnerableElement = can.Control('VulnerableElement', {
    pluginName: 'vulnerableElement'
}, {
    init: function () {
        this.childrenContainer = this.element.find('> .panel-body > .js-child-vulnerability-elements');
        var children = this.childrenContainer.children('.js-vulnerability-block');
        this.childrenIdCounter = children.length;
        children.vulnerableElement();
        this.childrenContainer.sortable();
        //this.childrenContainer.disableSelection();

        this.vulnList = this.element.find('> .panel-body > .js-vulnerability-set .js-vulnerability-list');
        this.conditionBlock = this.element.find('> .panel-body > .vulnerability-conditions-block');
        this.conditionList = this.conditionBlock.find('.js-condition-list');
        var controller = this;
        this.vulnList.children('.js-vulnerability').each(function () {
            controller.enablePlugin($(this));
        });
        //this.vulnIdCounter = this.vulnList.children('.js-vulnerability').length;

        if (this.element.parents('.js-vulnerability-block').length == 0) {
            this.element.find('> .panel-heading .js-remove').remove();
        }

        if (parseInt(this.element.closest('.js-context-panel').data('edit-mode'), 10) == 0) {
            this.element.find('> .panel-heading .js-collapsible-field').collapsibleField({
                emptyValue: 'Click to set block name...'
            });
        }

        this.conditionBlock.conditionsBlock({link: this.element.find('> .panel-heading > .js-show-conditions')})
    },

    '> .panel-body > .js-vulnerability-set .js-remove-vulnerability click': function (el, ev) {
        ev.preventDefault();
        el.closest('.js-vulnerability').remove();
    },

    '> .panel-body > .vulnerability-conditions-block .js-remove-condition click': function (el, ev) {
        ev.preventDefault();
        el.closest('.js-condition-row').remove();
    },

    '> .panel-heading .js-add-child click': function (el, ev) {
        ev.preventDefault();
        this.addChild();
    },

    '> .panel-heading .js-remove click': function (el, ev) {
        ev.preventDefault();
        el.closest('.js-vulnerability-block').remove();
    },

    '> .panel-heading .js-add-vulnerability-selector click': function (el, ev) {
        ev.preventDefault();

        var existingVulns = this.vulnList.children('.js-vulnerability').map(function (i, vulnElem) {
            return $(vulnElem).data('name');
        }).toArray();

        var options = $.map(this.getAllVulns(), function (val) {
            if ($.inArray(val, existingVulns) !== -1) {
                return '';
            }
            return '
' + val + '
';
        }).join('');
        el.next('.dropdown-menu').first().html(options);
    },

    '> .panel-heading .js-add-vulnerability click': function (el, ev) {
        ev.preventDefault();
        var vulnerability = el.data('vulnerability');

        var idBase = this.element.data('id') + '_vulnerabilitySet';
        var name = this.element.data('name') + '[vulnerabilitySet]';
        var template = can.view("#tplVulnerability_" + vulnerability, {id: idBase, name: name});
        var vulns = this.vulnList.find('.js-vulnerability');
        if (vulns.length) {
            var curVuln = null, greaterVuln = null;
            for (var i = 0; i < vulns.length; i++) {
                curVuln = vulns.eq(i);
                if (curVuln.data('name').toLowerCase() > vulnerability.toLowerCase()) {
                    greaterVuln = curVuln;
                    break;
                }
            }

            if (greaterVuln) {
                greaterVuln.before(template);
            } else {
                this.vulnList.append(template);
            }

        } else {
            this.vulnList.append(template);
        }

        var newVulnElement = this.vulnList.children('#' + idBase + '_vulnerabilities_' + vulnerability);
        this.enablePlugin(newVulnElement);
    },

    '> .panel-heading .js-add-condition-selector click': function (el, ev) {
        ev.preventDefault();

        var existingConditions = this.conditionList.children('.js-condition-row').map(function (i, condElem) {
            return $(condElem).data('name');
        }).toArray();

        var options = $.map(this.getAllConditions(), function (val) {
            if ($.inArray(val, existingConditions) !== -1) {
                return '';
            }
            return '
' + val + '
';
        }).join('');
        el.next('.dropdown-menu').first().html(options);
    },

    '> .panel-heading .js-add-condition click': function (el, ev) {
        ev.preventDefault();
        var condition = el.data('condition');

        var idBase = this.element.data('id') + '_conditionSet_';
        var name = this.element.data('name') + '[conditionSet]';
        var template = can.view("#tplCondition_" + condition, {id: idBase, name: name});
        var conditions = this.conditionList.find('.js-condition-row');
        if (conditions.length) {
            var curCond = null, greaterCondition = null;
            for (var i = 0; i < conditions.length; i++) {
                curCond = conditions.eq(i);
                if (curCond.data('name').toLowerCase() > condition.toLowerCase()) {
                    greaterCondition = curCond;
                    break;
                }
            }

            if (greaterCondition) {
                greaterCondition.before(template);
            } else {
                this.conditionList.append(template);
            }

        } else {
            this.conditionList.append(template);
        }

        this.conditionBlock.conditionsBlock('show');
    },

    addChild: function () {
        var idBase = this.element.data('id') + '_children';
        var name = this.element.data('name') + '[children]';
        var id = this.childrenIdCounter++;
        var template = can.view("#tplVulnerableElement", {id: idBase + '_' + id, name: name + '[' + id + ']'});
        this.childrenContainer.append(template);
        console.log('#' + idBase + '_' + id);
        this.childrenContainer.children('#' + idBase + '_' + id).vulnerableElement();
    },

    getVulnInfo: function () {
        return window.VulnInfo || {};
    },

    getAllVulns: function () {
        return (this.element.closest('.js-field-block').length > 0 ? this.getVulnInfo().fieldVulns : this.getVulnInfo().vulns) || [];
    },

    getAllConditions: function () {
        return this.getVulnInfo().conditions || [];
    },

    enablePlugin: function (el) {
        var pluginName = el.data('controller-plugin');
        if (pluginName && jQuery.fn[pluginName]) {
            el[pluginName]();
        }
    }
});

can.Control('IntegerOverflowVulnerability', {
    pluginName: 'integerOverflowVulnerability'
}, {
    init: function () {
        this.attrsElement = this.element.find('.js-vuln-attrs');
        this.enableCheckbox = this.element.find('.js-enable-vuln');
        this.hideOrShowAttrs();
    },

    '.js-enable-vuln change': function () {
        this.hideOrShowAttrs();
    },

    hideOrShowAttrs: function () {
        if (this.enableCheckbox.is(':checked')) {
            this.hide();
        } else {
            this.show();
        }
    },

    show: function () {
        this.attrsElement.show();
    },

    hide: function () {
        this.attrsElement.hide();
    }
});

can.Control('CollapsibleField', {
    pluginName: 'collapsibleField',
    defaults: {
        placeholder: null,
        emptyValue: 'Click to set name'
    }
}, {
    init: function () {
        if (!this.options.placeholder || !this.options.placeholder.length) {
            this.placeholder = $('');
            this.placeholder.insertAfter(this.element);

        } else {
            this.placeholder = this.options.placeholder;
        }

        this.options.placeholder = this.placeholder;
        this.on();

        this.hide();
        this.refreshPlaceholderText();
    },

    '{placeholder} click': function (el, ev) {
        ev.preventDefault();
        this.show();
    },

    setPlaceholderText: function (text) {
        this.placeholder.text('(' + text + ')');
    },

    refreshPlaceholderText: function () {
        var text = this.element.val() || this.options.emptyValue;
        this.setPlaceholderText(text);
    },

    hide: function () {
        this.element.hide();
        this.placeholder.show();
    },

    show: function () {
        this.element.show();
        this.placeholder.hide();
        this.element.focus();
    }
});

can.Control('PHPSessionIdOverflowVulnerability', {
    pluginName: 'phpSessionIdOverflowVulnerability'
}, {
    init: function () {
        this.attrsElement = this.element.find('.js-vuln-attrs');
        this.enableCheckbox = this.element.find('.js-enable-vuln');
        this.hideOrShowAttrs();
    },

    '.js-enable-vuln change': function () {
        this.hideOrShowAttrs();
    },

    hideOrShowAttrs: function () {
        if (this.enableCheckbox.is(':checked')) {
            this.hide();
        } else {
            this.show();
        }
    },

    show: function () {
        this.attrsElement.show();
    },

    hide: function () {
        this.attrsElement.hide();
    }
});

jQuery(function ($) {
    var $controlForm = $('#controlForm');

    $('#contextName, #editModeCheckbox').on('change', function (ev) {
        $controlForm.submit();
    });

    $('.context-panel').contextControl();
});


text:
<form>
    <field>
        <id>host.enabled</id>
        Enabled
        <type>checkbox</type>
        <help>Enable the override for this host</help>
    </field>
    <field>
        <id>host.hostname</id>
        Host
        <type>text</type>
        <help>Name of the host, without the domain part. Use "*" to create a wildcard entry.</help>
    </field>
    <field>
        <id>host.domain</id>
        Domain
        <type>text</type>
        <help>Domain of the host, e.g. example.com</help>
    </field>
    <field>
        <id>host.rr</id>
        Type
        <type>dropdown</type>
        <help>Type of resource record, e.g. A or AAAA for IPv4 or IPv6 addresses</help>
    </field>
    <field>
        <id>host.mxprio</id>
        MX Priority
        <type>text</type>
        <help>Priority of MX record, e.g. 10</help>
    </field>
    <field>
        <id>host.mx</id>
        MX Host
        <type>text</type>
        <help>Host name of MX host, e.g. mail.example.com</help>
    </field>
    <field>
        <id>host.server</id>
        IP address
        <type>text</type>
        <help>IP address of the host, e.g. 192.168.100.100 or fd00:abcd::1</help>
    </field>
    <field>
        <id>host.description</id>
        Description
        <type>text</type>
        <help>You may enter a description here for your reference (not parsed)</help>
    </field>
</form>


text:
'use strict'

var service = require('services/recinto.junta.service');

function queryJunta(req, res) {
    var q = req.query.q;
    var fields = req.query.fields;
    var sort = req.query.sort;
    var page = req.query.page;
    var perPage = req.query.per_page;

    service.query(req.params.id_recinto, q, fields, sort, page, perPage)
        .then(function (response) {
            if (response.juntas) {
                res.header('X-Total-Count',response.count);
                res.send(response.juntas);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
};

function getJuntaById(req, res) {
    service.getById(req.params.id_recinto, req.params._id)
        .then(function (obj) {
            if (obj) {
                res.send(obj);
            } else {
                res.sendStatus(404);
            }
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
};

function createJunta(req, res) {
    service.create(req.params.id_recinto, req.body)
        .then(function () {
            res.sendStatus(200);
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
};

function updateJunta(req, res) {
    service.update(req.params.id_recinto, req.params._id, req.body)
        .then(function () {
            res.sendStatus(200);
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
};

function deleteJunta(req, res) {
    service.delete(req.params.id_recinto, req.params._id)
        .then(function () {
            res.sendStatus(200);
        })
        .catch(function (err) {
            res.status(400).send(err);
        });
};

module.exports.queryJunta = queryJunta;
module.exports.getJuntaById = getJuntaById;
module.exports.createJunta = createJunta;
module.exports.updateJunta = updateJunta;
module.exports.deleteJunta = deleteJunta;


text:
package org.spongepowered.common.registry;

import static com.google.common.base.Preconditions.checkNotNull;

import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.spongepowered.lwts.runner.LaunchWrapperParameterized;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Optional;
import java.util.Set;

@RunWith(LaunchWrapperParameterized.class)
public class CatalogTypeMethodTest {

    private static final Logger LOG = LoggerFactory.getLogger(CatalogTypeMethodTest.class);

    @Parameterized.Parameters(name = "{index} Catalog Type: {0} Id : {3} Method: {5} ({6})")
    public static Iterable<Object[]> data() throws Exception {
        return RegistryTestUtil.generateCatalogTypeMethodTestObjects();
    }

    // TODO: Fix this list
    private static final Set<String> ignoredFailures = ImmutableSet.<String>builder()
            .add("org.spongepowered.common.statistic.SpongeEntityStatistic#getEntityType()")
            .add("org.spongepowered.common.world.gen.SpongePopulatorType#getTranslation()")
            .add("net.minecraft.util.EnumHand#getTranslation()")
            // AbstractMethodErrors
            .add("net.minecraft.block.BlockDirt$DirtType#getTranslation()")
            .add("net.minecraft.block.BlockPistonExtension$EnumPistonType#getTranslation()")
            .add("net.minecraft.block.BlockPrismarine$EnumType#getTranslation()")
            .add("net.minecraft.block.BlockQuartz$EnumType#getTranslation()")
            .add("net.minecraft.block.BlockSand$EnumType#getTranslation()")
            .add("net.minecraft.block.BlockSandStone$EnumType#getTranslation()")
            .add("net.minecraft.block.BlockStone$EnumType#getTranslation()")
            .add("net.minecraft.block.BlockStoneBrick$EnumType#getTranslation()")
            .add("net.minecraft.block.BlockStoneSlab$EnumType#getTranslation()")
            .add("net.minecraft.block.BlockStoneSlabNew$EnumType#getTranslation()")
            .add("net.minecraft.item.ItemArmor$ArmorMaterial#getRepairItemType()")
            .build();

    // Ignored translation prefixes + whether it was provided by sponge
    private static final Map<String, Boolean> ignoredTranslationPrefixes = ImmutableMap.<String, Boolean>builder()
            .put("sponge.statistic.type.", true)
            .put("item.", false)
            .put("entity.", false)
            .put("stat.", false)
            .put("tile.", false)
            .put("potion.effect.missing", false) // Needs API changes
            .put("gameMode.", false)
            .build();

    @Parameterized.Parameter(0)
    public String name;
    @Parameterized.Parameter(1)
    public Class<? extends CatalogType> catalogClass;
    @Parameterized.Parameter(2)
    public CatalogType catalogType;
    @Parameterized.Parameter(3)
    public String catalogId;
    @Parameterized.Parameter(4)
    public Method method;
    @Parameterized.Parameter(5)
    public String methodName;
    @Parameterized.Parameter(6)
    public String implementationClass;

    @Test
    public void testCatalogMethodImpl() throws Throwable {
        try {
            try {
                testResult(checkNotNull(this.method.invoke(this.catalogType), "return value"));
            } catch (InvocationTargetException e) {
                // Unwrap exception to avoid useless stacktrace entries
                if (e.getCause() != null) {
                    throw e.getCause();
                }
                throw e;
            }
        } catch (Throwable t) {
            if (ignoredFailures.contains(this.implementationClass + "#" + this.method.getName() + "()")) {
//                LOG.warn("Catalog Type: {} Id : {} has broken Method: {} ({}): {}", this.name, this.catalogId, this.methodName, this.implementationClass, t);
                return;
            }
            throw t;
        }
    }

    private void testResult(Object object) {
        checkNotNull(object, "contained value");
        if (object instanceof Optional) {
            ((Optional<?>) object).ifPresent(this::testResult);
        }
        if (object instanceof Iterable) {
            int index = 0;
            for (Object elem : (Iterable<?>) object) {
                try {
                    testResult(elem);
                    index++;
                } catch (Throwable t) {
                    throw new RuntimeException("Failed on sub-element: " + index, t);
                }
            }
        }
        if (object instanceof Translatable) {
            testResult(((Translatable) object).getTranslation());
        }
        if (object instanceof Translation) {
            Translation translation = (Translation) object;
            String translationId = checkNotNull(translation.getId(), "translationId");
            String translated = checkNotNull(translation.get(), "translated");
            if (translationId.equals(translated)) {
                boolean ignore = false;
                boolean silent = false;
                for (Entry<String, Boolean> entry : ignoredTranslationPrefixes.entrySet()) {
                    if (translationId.startsWith(entry.getKey())) {
                        ignore = true;
                        silent = entry.getValue();
                    }
                }
                if (silent) {
                    // Do nothing
                } else if (ignore) {
                    // Disabling logging for now, until someone ends up fixing the translations and tests.
                   // LOG.warn("Catalog Type: {} Id : {} fails to provide translation: '{}' in {} ({})", this.name, this.catalogId, translationId, this.methodName, this.implementationClass);
                } else {
                    throw new RuntimeException("No translation present for " + translationId);
                }
            }
        }
    }

}


text:
layout: post
title: Collection of Neural Network Visualization Tools
excerpt: "Collection of Neural Network Visualization Tools"
tags: [Linux, Code, Neural Network, Visualization, algorithms, concurrency, gpu, parallel]
comments: true
---

**Disclaimer** [^1]

## Tools to Design or Visualize Architecture of Neural Network

1. [**Net2Vis**](https://viscom.net2vis.uni-ulm.de/OG1Br2BAkYSwwrV6CADl4X5EfErFjUzvuUwXWDdLbdsIXNhb9L): Net2Vis automatically generates abstract visualizations for convolutional neural networks from Keras code.

![](https://storage.googleapis.com/groundai-web-prod/media/users/user_299833/project_401171/images/application.png)

2. [**visualkeras**](https://github.com/paulgavrikov/visualkeras/) :  Visualkeras is a Python package to help visualize Keras (either standalone or included in tensorflow) neural network architectures. It allows easy styling to fit most needs. As of now it supports layered style architecture generation which is great for CNNs (Convolutional Neural Networks) and a grap style architecture.

```python
import visualkeras

model = ...

visualkeras.layered_view(model).show() # display using your system viewer
visualkeras.layered_view(model, to_file='output.png') # write to disk
visualkeras.layered_view(model, to_file='output.png').show() # write and show

visualkeras.layered_view(model)
```

![](https://github.com/paulgavrikov/visualkeras/raw/master/figures/vgg16.png)

3. [**draw_convnet**](https://github.com/gwding/draw_convnet) : Python script for illustrating Convolutional Neural Network (ConvNet)

 ![img](https://raw.githubusercontent.com/gwding/draw_convnet/master/convnet_fig.png)

4. [**NNSVG**](http://alexlenail.me/NN-SVG/LeNet.html)

 ![AlexNet style](https://i.stack.imgur.com/Q0xOe.png)

 ![enter image description here](https://i.stack.imgur.com/K9lmg.png)

 ![enter image description here](https://i.stack.imgur.com/DlJ8J.png)

5. **[PlotNeuralNet](https://github.com/HarisIqbal88/PlotNeuralNet)**  : Latex code for drawing neural networks for reports and presentation. Have a look into examples to see how they are made. Additionally, lets consolidate any improvements that you make and fix any bugs to help more people with this code.

 ![img](https://user-images.githubusercontent.com/17570785/50308846-c2231880-049c-11e9-8763-3daa1024de78.png)

 ![img](https://user-images.githubusercontent.com/17570785/50308873-e2eb6e00-049c-11e9-9587-9da6bdec011b.png)

6. **[Tensorboard](https://www.tensorflow.org/tensorboard/graphs)** -  TensorBoard's **Graphs dashboard** is a powerful tool for examining your TensorFlow model.

 ![enter image description here](https://i.stack.imgur.com/zJHpV.png)

7. **[Caffe](https://github.com/BVLC/caffe/blob/master/python/caffe/draw.py)** -  In Caffe you can use [caffe/draw.py](https://github.com/BVLC/caffe/blob/master/python/caffe/draw.py) to draw the NetParameter protobuffer:

 ![enter image description here](https://i.stack.imgur.com/5Z1Cb.png)

8. **[Matlab](http://www.mathworks.com/help/nnet/ref/view.html)**

 ![enter image description here](https://i.stack.imgur.com/rPpfa.png)

9. [**Keras.js**](https://transcranial.github.io/keras-js/#/inception-v3)

 ![enter image description here](https://i.stack.imgur.com/vEfTv.png)

9. **[keras-sequential-ascii](https://github.com/stared/keras-sequential-ascii/)** -  A library for [Keras](https://keras.io/) for investigating architectures and parameters of sequential models.

**VGG 16 Architecture**

```
           OPERATION           DATA DIMENSIONS   WEIGHTS(N)   WEIGHTS(%)

              Input   #####      3  224  224
         InputLayer     |   -------------------         0     0.0%
                      #####      3  224  224
      Convolution2D    \|/  -------------------      1792     0.0%
               relu   #####     64  224  224
      Convolution2D    \|/  -------------------     36928     0.0%
               relu   #####     64  224  224
       MaxPooling2D   Y max -------------------         0     0.0%
                      #####     64  112  112
      Convolution2D    \|/  -------------------     73856     0.1%
               relu   #####    128  112  112
      Convolution2D    \|/  -------------------    147584     0.1%
               relu   #####    128  112  112
       MaxPooling2D   Y max -------------------         0     0.0%
                      #####    128   56   56
      Convolution2D    \|/  -------------------    295168     0.2%
               relu   #####    256   56   56
      Convolution2D    \|/  -------------------    590080     0.4%
               relu   #####    256   56   56
      Convolution2D    \|/  -------------------    590080     0.4%
               relu   #####    256   56   56
       MaxPooling2D   Y max -------------------         0     0.0%
                      #####    256   28   28
      Convolution2D    \|/  -------------------   1180160     0.9%
               relu   #####    512   28   28
      Convolution2D    \|/  -------------------   2359808     1.7%
               relu   #####    512   28   28
      Convolution2D    \|/  -------------------   2359808     1.7%
               relu   #####    512   28   28
       MaxPooling2D   Y max -------------------         0     0.0%
                      #####    512   14   14
      Convolution2D    \|/  -------------------   2359808     1.7%
               relu   #####    512   14   14
      Convolution2D    \|/  -------------------   2359808     1.7%
               relu   #####    512   14   14
      Convolution2D    \|/  -------------------   2359808     1.7%
               relu   #####    512   14   14
       MaxPooling2D   Y max -------------------         0     0.0%
                      #####    512    7    7
            Flatten   ||||| -------------------         0     0.0%
                      #####       25088
              Dense   XXXXX ------------------- 102764544    74.3%
               relu   #####        4096
              Dense   XXXXX -------------------  16781312    12.1%
               relu   #####        4096
              Dense   XXXXX -------------------   4097000     3.0%
            softmax   #####        1000
```

10. **[ Netron ](https://github.com/lutzroeder/Netron)**

 ![screenshot.png](https://github.com/lutzroeder/netron/raw/main/.github/screenshot.png)

11. **[DotNet](https://github.com/martisak/dotnets)**

 ![Simple net](https://github.com/martisak/dotnets/raw/master/test.png)

12. [**Graphviz**](http://www.graphviz.org/) : **[Tutorial](https://tgmstat.wordpress.com/2013/06/12/draw-neural-network-diagrams-graphviz/)**

 ![img](https://tgmstat.files.wordpress.com/2013/05/multiclass_neural_network_example.png)

13. **[Keras Visualization](https://keras.io/visualization/)** -  The [keras.utils.vis_utils module](https://keras.io/visualization/) provides utility functions to plot a Keras model (using graphviz)

 ![enter image description here](https://i.stack.imgur.com/o17GY.png)

14. **[Conx](https://conx.readthedocs.io/en/latest/index.html)** -  The Python package `conx` can visualize networks with activations with the function `net.picture()` to produce SVG, PNG, or PIL Images like this:

 ![enter image description here](https://i.stack.imgur.com/nhHjO.png)

15. **[ENNUI](https://math.mit.edu/ennui/)** -  Working on a drag-and-drop neural network visualizer (and more). Here's an example of a visualization for a LeNet-like architecture.

 ![A visualization of a LeNet-like architecture](https://i.stack.imgur.com/pRLeG.png)

16. **NNet - R Package** - **[Tutorial](https://beckmw.wordpress.com/2013/03/04/visualizing-neural-networks-from-the-nnet-package/)**

```
data(infert, package="datasets")
plot(neuralnet(case~parity+induced+spontaneous, infert))
```

[![neuralnet](https://i.stack.imgur.com/yyftd.png)](https://

17. **[GraphCore](https://www.graphcore.ai/posts/what-does-machine-learning-look-like)** -  These approaches are more oriented towards visualizing neural network operation, however, NN architecture is also somewhat visible on the resulting diagrams.

**AlexNet**

 ![alexnet_label logo.jpg](https://www.graphcore.ai/hubfs/images/alexnet_label%20logo.jpg)

 **ResNet50**![resnet50_label_logo.jpg](https://www.graphcore.ai/hubfs/images/resnet50_label_logo.jpg)

18.  [**Neataptic**](https://wagenaartje.github.io/neataptic/ )

Neataptic offers flexible neural networks; neurons and synapses can be removed with a single line of code. No fixed architecture is required for neural networks to function at all. This flexibility allows networks to be shaped for your dataset through neuro-evolution, which is done using multiple threads.

 ![img](https://camo.githubusercontent.com/4326c3f603b828b61fd63d927acca2cfc152773f/68747470733a2f2f692e6779617a6f2e636f6d2f66353636643233363461663433646433613738633839323665643230346135312e706e67)

19. **[TensorSpace](https://tensorspace.org/)** :  TensorSpace is a neural network 3D visualization framework built by TensorFlow.js, Three.js and Tween.js. TensorSpace provides Layer APIs to build deep learning layers, load pre-trained models, and generate a 3D visualization in the browser. By applying TensorSpace API, it is more intuitive to visualize and understand any pre-trained models built by TensorFlow, Keras, TensorFlow.js, etc.

    **[Tutorial](https://www.freecodecamp.org/news/tensorspace-js-a-way-to-3d-visualize-neural-networks-in-browsers-2c0afd7648a8/)**

     ![enter image description here](https://i.stack.imgur.com/ekF5v.png)

20. **[Netscope CNN Analyzer](http://dgschwend.github.io/netscope/quickstart.html)**

 ![enter image description here](https://i.stack.imgur.com/VVDsg.png)

21. **[Monial](https://github.com/mlajtos/moniel)**

 Interactive Notation for Computational Graphs https://mlajtos.github.io/moniel/

 ![img](https://miro.medium.com/max/819/1*u6uIQF4xTVe-ylJnAPoIDg.png)

22. [**Texample**](http://www.texample.net/tikz/examples/neural-network/)

![Neural Network](https://texample.net/media/tikz/examples/PNG/neural-network.png)

```
\documentclass{article}

\usepackage{tikz}
\begin{document}
\pagestyle{empty}

\def\layersep{2.5cm}

\begin{tikzpicture}[shorten >=1pt,->,draw=black!50, node distance=\layersep]
    \tikzstyle{every pin edge}=[<-,shorten <=1pt]
    \tikzstyle{neuron}=[circle,fill=black!25,minimum size=17pt,inner sep=0pt]
    \tikzstyle{input neuron}=[neuron, fill=green!50];
    \tikzstyle{output neuron}=[neuron, fill=red!50];
    \tikzstyle{hidden neuron}=[neuron, fill=blue!50];
    \tikzstyle{annot} = [text width=4em, text centered]

    % Draw the input layer nodes
    \foreach \name / \y in {1,...,4}
    % This is the same as writing \foreach \name / \y in {1/1,2/2,3/3,4/4}
        \node[input neuron, pin=left:Input \#\y] (I-\name) at (0,-\y) {};

    % Draw the hidden layer nodes
    \foreach \name / \y in {1,...,5}
        \path[yshift=0.5cm]
            node[hidden neuron] (H-\name) at (\layersep,-\y cm) {};

    % Draw the output layer node
    \node[output neuron,pin={[pin edge={->}]right:Output}, right of=H-3] (O) {};

    % Connect every node in the input layer with every node in the
    % hidden layer.
    \foreach \source in {1,...,4}
        \foreach \dest in {1,...,5}
            \path (I-\source) edge (H-\dest);

    % Connect every node in the hidden layer with the output layer
    \foreach \source in {1,...,5}
        \path (H-\source) edge (O);

    % Annotate the layers
    \node[annot,above of=H-1, node distance=1cm] (hl) {Hidden layer};
    \node[annot,left of=hl] {Input layer};
    \node[annot,right of=hl] {Output layer};
\end{tikzpicture}
% End of code
\end{document}
```

23. [**Quiver**](https://github.com/keplr-io/quiver)

 ![gzqll3](https://cloud.githubusercontent.com/assets/5866348/20253975/f3d56f14-a9e4-11e6-9693-9873a18df5d3.gif)

**References :**

1)  https://datascience.stackexchange.com/questions/12851/how-do-you-visualize-neural-network-architectures

2)   https://datascience.stackexchange.com/questions/2670/visualizing-deep-neural-network-training

[^1]: The work of collecting all these tools in a single location is done in
    [this
    repo](https://github.com/ashishpatel26/Tools-to-Design-or-Visualize-Architecture-of-Neural-Network/blob/master/README.md)
    (not mine). Please go over there and show some love to the developer who put
    this together. I like it so much that I felt the need to save this here. In
    the true spirit of this blog, it's meant to be my rough notes.


text:
'use strict';

var cluster    = require('cluster');
var logfmt     = require('logfmt');
var prettysize = require('prettysize');

/**
 * Monitors and logs the memory usage of a worker process and kills the process
 * when a limit is exceeded.
 *
 * @class WorkerMonitor
 * @constructor
 * @param {Worker} worker the Node worker to monitor
 * @param {Object} [options={}] options to override defaults
 * @param {Number} [options.disconnectTimeout=5000] the time after which a
 *   disconnecting worker should be killed immediately
 * @param {Number,null} [options.logPeriod=10000] the period (in milliseconds)
 *   on which to log the worker's memory usage
 * @param {Number,null} [options.monitorPeriod=10000] the period (in
 *   milliseconds) on which to monitor the worker's memory usage
 * @param {Number} [options.memoryLimit=220000000] the memory usage limit (in bytes) of the
 *   worker process
 */
function WorkerMonitor(worker, options) {
  options = options || {};

  /**
   * The worker to be monitored and killed if its RSS exceeds
   * {{#crossLink "WorkerMonitor/memoryLimit:property"}}`memoryLimit`{{/crossLink}}
   *
   * @property worker
   * @type Worker
   */
  this.worker = worker;

  /**
   * The timeout after attempting to disconnect a worker when the worker is
   * killed forcefully.
   *
   * @property disconnectTimeout
   * @type Number
   * @default 5000
   */
  this.disconnectTimeout = options.disconnectTimeout || 5000;

  /**
   * The period on which the worker's memory is logged. If null, memory will not
   * be logged.
   *
   * @property logPeriod
   * @type Number,null
   * @default 10000
   */
  this.logPeriod = options.logPeriod === undefined ? 10000 : options.logPeriod;

  /**
   * The period on which the worker has its memory checked and is possibly
   * disconnected. If null, memory will not be monitored (this allows for only
   * logging memory).
   *
   * @property monitorPeriod
   * @type Number,null
   * @default 10000
   */
  this.monitorPeriod = options.monitorPeriod === undefined ? 10000 : options.monitorPeriod;

  /**
   * The limit (in bytes) that a process's RSS can grow to before it is killed.
   *
   * @property memoryLimit
   * @type Number
   * @default 220000000
   */
  this.memoryLimit = options.memoryLimit || 220000000;

  /**
   * The interval ID referring to the interval that calls the monitor function.
   *
   * @property monitorInterval
   * @private
   * @type Number,null
   */
  this.monitorInterval = this.getMonitorInterval();

  /**
   * The interval ID referring to the interval that calls the logging function.
   *
   * @property logInterval
   * @private
   * @type Number,null
   */
  this.logInterval = this.getLogInterval();

  /**
   * The source string, used in logging, for identifying this particular worker.
   *
   * @property source
   * @private
   * @type String
   */
  this.source = cluster.isMaster ? 'master' : 'worker.' + worker.id;
}

/**
 * Kill the worker by disconnecting it, and then killing it when a timeout is
 * exceeded.
 *
 * @method disconnectWorker
 * @private
 */
WorkerMonitor.prototype.disconnectWorker = function workerMonitorDisconnectWorker() {
  logfmt.log({
    source : 'master',
    message: 'worker exceeded memory limit',
    worker : this.worker.id,
    pid    : this.worker.process.pid,
    'count#worker-exceeded-memory': 1
  });

  process.send('workerExceededMemory');
  this.worker.disconnect();

  var killTimeout = setTimeout(function() {
    this.killWorker();
  }.bind(this), this.disconnectTimeout);

  killTimeout.unref();

  this.worker.on('disconnect', function() {
    clearTimeout(killTimeout);
  }.bind(this));
};

/**
 * Kill the worker process immediately by sending it `SIGINT`.
 *
 * @method killWorker
 * @private
 */
WorkerMonitor.prototype.killWorker = function workerMonitorKillWorker() {
  logfmt.log({
    source : 'master',
    message: 'worker failed to disconnect by timeout',
    worker : this.worker.id,
    pid    : this.worker.process.pid,
    'count#worker-disconnect-failed': 1
  });

  this.worker.kill('SIGINT');
};

/**
 * Return the ID for an interval on which to log the memory usage of this
 * worker. Returns `null` if
 * {{#crossLink "WorkerMonitor/logPeriod:property"}}`logPeriod`{{/crossLink}} is
 * `null`.
 *
 * @method getLogInterval
 * @private
 * @return {Number,null} an interval ID or `null`
 */
WorkerMonitor.prototype.getLogInterval = function workerMonitorGetLogInterval() {
  var logFn = this.log.bind(this);

  if (this.logPeriod !== null) {
    return setInterval(logFn, this.logPeriod);
  } else {
    return null;
  }
};

/**
 * Return the ID for an interval on which to monitor the memory usage of this
 * worker. Returns `null` if
 * {{#crossLink "WorkerMonitor/monitorPeriod:property"}}`monitorPeriod`{{/crossLink}}
 * is `null`.
 *
 * @method getMonitorInterval
 * @private
 * @return {Number,null} an interval ID or null
 */
WorkerMonitor.prototype.getMonitorInterval = function workerMonitorGetMonitorInterval() {
  var monitorFn = this.monitor.bind(this);

  if (this.monitorPeriod !== null) {
    return setInterval(monitorFn, this.monitorPeriod);
  } else {
    return null;
  }
};

/**
 * Log the memory usage of the worker.
 *
 * @method log
 * @private
 */
WorkerMonitor.prototype.log = function workerMonitorLog() {
  var memoryUsage = process.memoryUsage();

  logfmt.log({
    source             : this.source,
    pid                : process.pid,
    'measure#rss'      : prettysize(memoryUsage.rss, true),
    'measure#heapTotal': prettysize(memoryUsage.heapTotal, true),
    'measure#heapUsed' : prettysize(memoryUsage.heapUsed, true)
  });
};

/**
 * Check the memory usage of the worker and start the graceful disconnect
 * process if the usage exceeds the memory limit.
 *
 * @method monitor
 * @private
 */
WorkerMonitor.prototype.monitor = function workerMonitorMonitor() {
  var rss = process.memoryUsage().rss;

  if (rss > this.memoryLimit) {
    clearInterval(this.monitorInterval);
    clearInterval(this.logInterval);
    this.disconnectWorker();
  }
};

module.exports = WorkerMonitor;


text:
<?php

/**
 * IAlterDatabaseStatement interface file.
 *
 * @author Anastaszor
 */
interface IAlterDatabaseStatement extends IExecutableStatement
{

	/**
	 *
	 * @return string
	 */
	public function getDatabaseName();

	/**
	 *
	 * @return IDatabaseSpecificationStatement
	 */
	public function getSpecification();

}


text:
class AddPmdocsCountAndPmcdocsCountAndDenotationsCountAndRelationsCountToProjects < ActiveRecord::Migration
  def up
    add_column :projects, :pmdocs_count, :integer, :default => 0
    add_column :projects, :pmcdocs_count, :integer, :default => 0
    add_column :projects, :denotations_count, :integer, :default => 0
    add_column :projects, :relations_count, :integer, :default => 0

    # set current count for each counter column
    Project.unscoped.each do |project|
      if project.type == 'Sproject'
        pmdocs_count = project.pmdocs.length
        pmcdocs_count = project.pmcdocs.length
        denotations_count = Denotation.projects_denotations(project.project_ids).length
        relations_count = Relation.projects_relations(project.project_ids).length
      else
        pmdocs_count = project.docs.pmdocs.length
        pmcdocs_count = project.docs.pmcdocs.length
        denotations_count = project.denotations.length
        relations_count = project.relations.length
      end
      Project.unscoped.update_counters project.id,
        :pmdocs_count => pmdocs_count,
        :pmcdocs_count => pmcdocs_count,
        :denotations_count => denotations_count,
        :relations_count => relations_count
    end
  end

  def down
    remove_column :projects, :pmdocs_count
    remove_column :projects, :pmcdocs_count
    remove_column :projects, :denotations_count
    remove_column :projects, :relations_count
  end
end


text:
/* NOTE: This file is autogenerated, do not edit this file directly.*/

#include <TRChartsJNI/Series.hpp>
#include <TRChartsJNI/Support/Marshallers.hpp>
#include <TRChartsJNI/Support/Handle.hpp>
#include <TRChartsJNI/Support/Utils.hpp>
#include <TRCharts/Series.hpp>

using namespace TRChartsJNI;

JNIEXPORT jobject JNICALL Java_com_thomsonreuters_corptech_charts_Series_nativeGetOrdinateAxis(JNIEnv * env, jobject obj, jlong ptr)
{
	try {
		Utils::threadEnter(env);
		Utils::EndScopeAction threadExitAction(Utils::threadExit);
		TRChartsJNI::Handle * const handle = reinterpret_cast<TRChartsJNI::Handle *>(ptr);
		return TRChartsJNI::getContinuousAxisMarshaller().unmarshall(env, handle->getNativeObject<Charts::Series>(env)->getOrdinateAxis());
	} catch (const std::exception & e) {
		Utils::throwJavaException(env, e.what());
	} catch (...) {
		Utils::throwJavaException(env, nullptr);
	}
}

JNIEXPORT void JNICALL Java_com_thomsonreuters_corptech_charts_Series_nativeSetOrdinateAxis(JNIEnv * env, jobject obj, jlong ptr, jobject value)
{
	try {
		Utils::threadEnter(env);
		Utils::EndScopeAction threadExitAction(Utils::threadExit);
		TRChartsJNI::Handle * const handle = reinterpret_cast<TRChartsJNI::Handle *>(ptr);
		handle->getNativeObject<Charts::Series>(env)->setOrdinateAxis(TRChartsJNI::getContinuousAxisMarshaller().marshall(env, value));
	} catch (const std::exception & e) {
		Utils::throwJavaException(env, e.what());
	} catch (...) {
		Utils::throwJavaException(env, nullptr);
	}
}
JNIEXPORT jobject JNICALL Java_com_thomsonreuters_corptech_charts_Series_nativeGetColor(JNIEnv * env, jobject obj, jlong ptr)
{
	try {
		Utils::threadEnter(env);
		Utils::EndScopeAction threadExitAction(Utils::threadExit);
		TRChartsJNI::Handle * const handle = reinterpret_cast<TRChartsJNI::Handle *>(ptr);
		return TRChartsJNI::getColorMarshaller().unmarshall(env, handle->getNativeObject<Charts::Series>(env)->getColor());
	} catch (const std::exception & e) {
		Utils::throwJavaException(env, e.what());
	} catch (...) {
		Utils::throwJavaException(env, nullptr);
	}
}

JNIEXPORT void JNICALL Java_com_thomsonreuters_corptech_charts_Series_nativeSetColor(JNIEnv * env, jobject obj, jlong ptr, jobject value)
{
	try {
		Utils::threadEnter(env);
		Utils::EndScopeAction threadExitAction(Utils::threadExit);
		TRChartsJNI::Handle * const handle = reinterpret_cast<TRChartsJNI::Handle *>(ptr);
		handle->getNativeObject<Charts::Series>(env)->setColor(TRChartsJNI::getColorMarshaller().marshall(env, value));
	} catch (const std::exception & e) {
		Utils::throwJavaException(env, e.what());
	} catch (...) {
		Utils::throwJavaException(env, nullptr);
	}
}

JNIEXPORT void JNICALL Java_com_thomsonreuters_corptech_charts_Series_nativeMarkDirty(JNIEnv * env, jobject obj, jlong ptr)
{
	try {
		Utils::threadEnter(env);
		Utils::EndScopeAction threadExitAction(Utils::threadExit);
		TRChartsJNI::Handle * const handle = reinterpret_cast<TRChartsJNI::Handle *>(ptr);
		handle->getNativeObject<Charts::Series>(env)->markDirty();
	} catch (const std::exception & e) {
		Utils::throwJavaException(env, e.what());
	} catch (...) {
		Utils::throwJavaException(env, nullptr);
	}
}

JNIEXPORT void JNICALL Java_com_thomsonreuters_corptech_charts_Series_nativeMarkRangeDirty(JNIEnv * env, jobject obj, jlong ptr, jobject range)
{
	try {
		Utils::threadEnter(env);
		Utils::EndScopeAction threadExitAction(Utils::threadExit);
		TRChartsJNI::Handle * const handle = reinterpret_cast<TRChartsJNI::Handle *>(ptr);
		handle->getNativeObject<Charts::Series>(env)->markRangeDirty(TRChartsJNI::getIndexRangeMarshaller().marshall(env, range));
	} catch (const std::exception & e) {
		Utils::throwJavaException(env, e.what());
	} catch (...) {
		Utils::throwJavaException(env, nullptr);
	}
}


text:
  npm install --save css-toggle-switch

  bower install --save css-toggle-switch


text:
.. _implementation:

SeaPy implementation
####################

.. toctree::
   :maxdepth: 2

The previous chapter explained what Statistical Energy Analysis is.
In this chapter we will have a closer look on how SEA is implemented.

=========
Overview
=========

An SEA model in SeaPy is represented by the descendents of the following abstract objects:

* :class:`seapy.components.component.Component`
* :class:`seapy.subsystems.subsystem.Subsystem`
* :class:`seapy.junctions.junction.Junction`
* :class:`seapy.couplings.coupling.Coupling`
* :class:`seapy.materials.material.Material`
* :class:`seapy.excitations.excitation.Excitation`

as well as the main class representing the model

* :class:`seapy.system.System`

The following figure gives an overview on how the classes are related.

.. graphviz::

    digraph overview {
      Subsystem -> Component -> System;
      Coupling -> Junction -> System;
      Junction -> Component
      Coupling -> Subsystem
      Coupling -> Component
      Component -> Material -> System
      Excitation -> Subsystem
    }

Components can have multiple subsystems. Depending on the type of component these are added automatically when creating a component.
If components are connected to eachother a Junction needs to be created. The Junction will automatically create all possible couplings between the subsystems.


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

<title>EmbeddedXADataSource (Apache Derby 10.10 API Documentation)</title>
<meta name="date" content="2014-03-27">
<link rel="stylesheet" type="text/css" href="../../../../stylesheet.css" title="Style">

JavaScript is disabled on your browser.

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Apache Derby 10.10

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

org.apache.derby.jdbc

Class EmbeddedXADataSource

java.lang.Object

org.apache.derby.jdbc.EmbeddedBaseDataSource

org.apache.derby.jdbc.ReferenceableDataSource

org.apache.derby.jdbc.EmbeddedDataSource

org.apache.derby.jdbc.EmbeddedXADataSource

All Implemented Interfaces:

java.io.Serializable, javax.naming.Referenceable, javax.naming.spi.ObjectFactory, javax.sql.DataSource, javax.sql.XADataSource, org.apache.derby.jdbc.EmbeddedDataSourceInterface, org.apache.derby.jdbc.EmbeddedXADataSourceInterface

public class EmbeddedXADataSource
extends EmbeddedDataSource
implements org.apache.derby.jdbc.EmbeddedXADataSourceInterface

This datasource is suitable for an application using embedded Derby,
    running on full Java SE 5 or 6, corresponding to JDBC 3.0 and 4.0.
    If running on Java SE 7 or higher, consider a more capable data source.

    EmbeddedXADataSource is an XADataSource implementation.

An XADataSource is a factory for XAConnection objects.  It represents a
        RM in a DTP environment.  An object that implements the XADataSource
        interface is typically registered with a JNDI service provider.

        EmbeddedXADataSource automatically supports the correct JDBC specification version
        for the Java Virtual Machine's environment.

 JDBC 3.0 - J2SE 5.0

 JDBC 4.0 - Java SE 6

EmbeddedXADataSource object only works on a local database.  There is no
        client/server support.  An EmbeddedXADataSource object must live in the same jvm as
        the database.

EmbeddedXADataSource is serializable and referenceable.

See EmbeddedDataSource for DataSource properties.

See Also:

Serialized Form

Field Summary

Fields inherited from class org.apache.derby.jdbc.EmbeddedBaseDataSource

attributesAsPassword, connectionAttributes, createDatabase, databaseName, dataSourceName, description, driver, jdbcurl, loginTimeout, shutdownDatabase

Constructor Summary

Constructors

Constructor and Description

EmbeddedXADataSource()

no-arg constructor

Method Summary

All Methods Instance Methods Concrete Methods

Modifier and Type
Method and Description

org.apache.derby.iapi.jdbc.ResourceAdapter
getResourceAdapter()

javax.sql.XAConnection
getXAConnection()

Attempt to establish a database connection.

javax.sql.XAConnection
getXAConnection(java.lang.String user,
               java.lang.String password)

Attempt to establish a database connection with the given user
 name and password.

protected void
update()

Methods inherited from class org.apache.derby.jdbc.EmbeddedDataSource

getReference

Methods inherited from class org.apache.derby.jdbc.ReferenceableDataSource

getObjectInstance

Methods inherited from class org.apache.derby.jdbc.EmbeddedBaseDataSource

equals, getAttributesAsPassword, getConnection, getConnection, getConnectionAttributes, getCreateDatabase, getDatabaseName, getDataSourceName, getDescription, getLoginTimeout, getLogWriter, getPassword, getShortDatabaseName, getShutdownDatabase, getUser, isWrapperFor, setAttributesAsPassword, setConnectionAttributes, setCreateDatabase, setDatabaseName, setDataSourceName, setDescription, setLoginTimeout, setLogWriter, setPassword, setShutdownDatabase, setupResourceAdapter, setUser, unwrap

Methods inherited from class java.lang.Object

clone, finalize, getClass, hashCode, notify, notifyAll, toString, wait, wait, wait

Methods inherited from interface org.apache.derby.jdbc.EmbeddedDataSourceInterface

getAttributesAsPassword, getConnectionAttributes, getCreateDatabase, getDatabaseName, getDataSourceName, getDescription, getPassword, getShutdownDatabase, getUser, setAttributesAsPassword, setConnectionAttributes, setCreateDatabase, setDatabaseName, setDataSourceName, setDescription, setPassword, setShutdownDatabase, setUser

Methods inherited from interface javax.sql.DataSource

getConnection, getConnection, getLoginTimeout, getLogWriter, setLoginTimeout, setLogWriter

Methods inherited from interface javax.sql.XADataSource

getLoginTimeout, getLogWriter, setLoginTimeout, setLogWriter

Constructor Detail

EmbeddedXADataSource

public EmbeddedXADataSource()

no-arg constructor

Method Detail

getXAConnection

public final javax.sql.XAConnection getXAConnection()
                                             throws java.sql.SQLException

Attempt to establish a database connection.

Specified by:

getXAConnection in interface javax.sql.XADataSource

Returns:

a Connection to the database

Throws:

java.sql.SQLException - if a database-access error occurs.

getXAConnection

public final javax.sql.XAConnection getXAConnection(java.lang.String user,
                                                    java.lang.String password)
                                             throws java.sql.SQLException

Attempt to establish a database connection with the given user
 name and password.

Specified by:

getXAConnection in interface javax.sql.XADataSource

Parameters:

user - the database user on whose behalf the Connection is being made

password - the user's password

Returns:

a Connection to the database

Throws:

java.sql.SQLException - if a database-access error occurs.

update

protected void update()

Overrides:

update in class org.apache.derby.jdbc.EmbeddedBaseDataSource

getResourceAdapter

public org.apache.derby.iapi.jdbc.ResourceAdapter getResourceAdapter()

Specified by:

getResourceAdapter in interface org.apache.derby.jdbc.EmbeddedXADataSourceInterface

Returns:

The ResourceAdapter instance for
         the underlying database

Skip navigation links

Overview

Package

Class

Tree

Deprecated

Index

Help

Built on Thu 2014-03-27 12:16:03-0700, from revision 1582446

Prev Class

Next Class

Frames

No Frames

All Classes

Summary:

Nested |

Field |

Constr |

Method

Detail:

Field |

Constr |

Method

Apache Derby 10.10 API Documentation  -  Copyright © 2004,2014 The Apache Software Foundation. All Rights Reserved.


text:
package org.oscm.auditlog.bean;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.mockito.Matchers.anyListOf;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.eq;
import static org.mockito.Mockito.doReturn;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.spy;
import static org.mockito.Mockito.times;
import static org.mockito.Mockito.verify;
import static org.oscm.auditlog.util.AuditLogFactory.createAuditLogEntries;
import static org.oscm.internal.types.enumtypes.ConfigurationKey.AUDIT_LOG_MAX_ENTRIES_RETRIEVED;
import static org.oscm.types.constants.Configuration.GLOBAL_CONTEXT;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.Callable;

import javax.ejb.Asynchronous;
import javax.enterprise.event.Observes;
import javax.enterprise.event.TransactionPhase;

import org.junit.Test;
import org.oscm.auditlog.dao.AuditLogDao;
import org.oscm.auditlog.model.AuditLog;
import org.oscm.auditlog.model.AuditLogEntries;
import org.oscm.auditlog.model.AuditLogEntry;
import org.oscm.auditlog.util.AuditLogSerializer;
import org.oscm.configurationservice.bean.ConfigurationServiceBean;
import org.oscm.configurationservice.local.ConfigurationServiceLocal;
import org.oscm.dataservice.bean.DataServiceBean;
import org.oscm.domobjects.ConfigurationSetting;
import org.oscm.internal.types.exception.AuditLogTooManyRowsException;
import org.oscm.test.EJBTestBase;
import org.oscm.test.cdi.ContextManager;
import org.oscm.test.cdi.ObserverMethod;
import org.oscm.test.ejb.TestContainer;
import org.oscm.test.stubs.ConfigurationServiceStub;

@SuppressWarnings("boxing")
public class AuditLogServiceBeanIT extends EJBTestBase {
    private AuditLogServiceBean logService;
    private ContextManager contextManager;
    private final List<String> operatorIds = new ArrayList<>();

    @Override
    protected void setup(TestContainer beanManager) throws Exception {
        beanManager.addBean(new ConfigurationServiceStub());
        beanManager.addBean(new DataServiceBean());
        beanManager.addBean(new ConfigurationServiceBean());
        beanManager.addBean(spy(new AuditLogDao()));
        beanManager.addBean(new AuditLogServiceBean());
        logService = spy(beanManager.get(AuditLogServiceBean.class));
        this.contextManager = beanManager.getContextManager();
    }

    @Test
    public void loadAuditLogs() throws Exception {
        // given
        List<AuditLog> auditLogs = new ArrayList<>();
        AuditLogServiceBean logService = mockAuditLogServiceBean(auditLogs);

        // when
        logService.loadAuditLogs(anyListOf(String.class), anyLong(), anyLong());

        // then
        verify(logService.createAuditLogSerializer(), times(1))
                .serialize(eq(auditLogs));
    }

    private AuditLogServiceBean mockAuditLogServiceBean(
            List<AuditLog> auditLogs) {
        doReturn(mock(AuditLogSerializer.class)).when(logService)
                .createAuditLogSerializer();
        logService.dao = mock(AuditLogDao.class);
        doReturn(auditLogs).when(logService.dao)
                .loadAuditLogs(anyListOf(String.class), anyLong(), anyLong());
        doReturn(100L).when(logService).getMaxAuditlogs();
        return logService;
    }

    @Test(expected = AuditLogTooManyRowsException.class)
    public void loadAuditLogs_tooManyRows() throws Exception {
        // given
        operatorIds.add("30000");
        doReturn(2L).when(logService).getMaxAuditlogs();
        givenAuditLogEntries("opName1", 3);

        // when
        loadAuditLogsInTx(operatorIds, 0, Long.MAX_VALUE);
    }

    private List<AuditLogEntry> givenAuditLogEntries(String operationName,
            int numberLogEntries) throws Exception {
        List<AuditLogEntry> logEntries = createAuditLogEntries(operationName,
                numberLogEntries);
        saveAuditLogInTx(logEntries);
        return logEntries;
    }

    private void saveAuditLogInTx(final List<AuditLogEntry> logEntries)
            throws Exception {
        runTX(new Callable<Void>() {
            @Override
            public Void call() {
                logService.dao.saveAuditLog(logEntries);
                return null;
            }
        });
    }

    private void logInTx(final List<AuditLogEntry> logEntries)
            throws Exception {
        runTX(new Callable<Void>() {
            @Override
            public Void call() {
                logService.log(logEntries);
                return null;
            }
        });
    }

    private byte[] loadAuditLogsInTx(final List<String> operationIds,
            final long startTime, final long endTime) throws Exception {
        return runTX(new Callable<byte[]>() {
            @Override
            public byte[] call() throws AuditLogTooManyRowsException {
                return logService.loadAuditLogs(operationIds, startTime,
                        endTime);
            }
        });
    }

    @Test
    public void loadAuditLogs_givenLogEntriesSameAsMaxAuditLogs()
            throws Exception {
        // given
        operatorIds.add("30000");
        doReturn(2L).when(logService).getMaxAuditlogs();
        givenAuditLogEntries("opName1", 2);

        // when
        loadAuditLogsInTx(operatorIds, 0, Long.MAX_VALUE);

        // then no exception
    }

    @Test
    public void loadAuditLogs_givenLogEntriesIsLessThanMaxAuditLogs()
            throws Exception {
        // given
        operatorIds.add("30000");
        doReturn(3L).when(logService).getMaxAuditlogs();
        givenAuditLogEntries("opName1", 2);

        // when
        loadAuditLogsInTx(operatorIds, 0, Long.MAX_VALUE);

        // then no exception
    }

    @Test
    public void log() throws Exception {
        // given
        List<AuditLogEntry> logEntries = createAuditLogEntries("opName1", 2);

        // when
        logInTx(logEntries);

        // then
        verify(logService.dao, times(1)).saveAuditLog(eq(logEntries));
    }

    public void log_isAsynchronous() throws Exception {
        // given
        Method method = AuditLogServiceBean.class.getMethod("log");

        // when
        boolean isAsynchronous = method.isAnnotationPresent(Asynchronous.class);

        // then
        assertTrue(isAsynchronous);
    }

    @Test
    public void saveAuditLogEntries_hasObserverMethodAfterSuccessAnnotation() {
        // given
        AuditLogEntries auditLogEntries = new AuditLogEntries(
                new ArrayList<AuditLogEntry>());
        List<ObserverMethod> observerMethods = contextManager
                .findObserverMethods(auditLogEntries);
        Method method = observerMethods.get(0).getMethod();

        // when
        Observes observes = (Observes) contextManager.searchAnnotation(method,
                Observes.class);

        // then
        assertEquals(TransactionPhase.AFTER_SUCCESS, observes.during());
    }

    @Test
    public void getMaxAuditlogs() {
        // given
        logService.configService = mock(ConfigurationServiceLocal.class);
        ConfigurationSetting setting = new ConfigurationSetting(
                AUDIT_LOG_MAX_ENTRIES_RETRIEVED, GLOBAL_CONTEXT, "876");
        doReturn(setting).when(logService.configService)
                .getConfigurationSetting(eq(AUDIT_LOG_MAX_ENTRIES_RETRIEVED),
                        eq(GLOBAL_CONTEXT));

        // when
        long maxAuditLogs = logService.getMaxAuditlogs();

        // then
        assertEquals(876, maxAuditLogs);
    }
}


text: Ansible Jenkins


text:
.class public abstract Lcom/google/android/gms/internal/zzlr;
.super Ljava/lang/Object;

# annotations
.annotation system Ldalvik/annotation/MemberClasses;
    value = {
        Lcom/google/android/gms/internal/zzlr$zza;
    }
.end annotation

.annotation system Ldalvik/annotation/Signature;
    value = {
        "<T:",
        "Ljava/lang/Object;",
        ">",
        "Ljava/lang/Object;"
    }
.end annotation

# static fields
.field private static zzadc:Lcom/google/android/gms/internal/zzlr$zza;

.field private static zzadd:I

.field private static zzade:Ljava/lang/String;

.field private static final zzpy:Ljava/lang/Object;

# instance fields
.field private zzOX:Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TT;"
        }
    .end annotation
.end field

.field protected final zzue:Ljava/lang/String;

.field protected final zzuf:Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "TT;"
        }
    .end annotation
.end field

# direct methods
.method static constructor <clinit>()V
    .registers 1

    new-instance v0, Ljava/lang/Object;

    invoke-direct {v0}, Ljava/lang/Object;-><init>()V

    sput-object v0, Lcom/google/android/gms/internal/zzlr;->zzpy:Ljava/lang/Object;

    const/4 v0, 0x0

    sput-object v0, Lcom/google/android/gms/internal/zzlr;->zzadc:Lcom/google/android/gms/internal/zzlr$zza;

    const/4 v0, 0x0

    sput v0, Lcom/google/android/gms/internal/zzlr;->zzadd:I

    const-string v0, "com.google.android.providers.gsf.permission.READ_GSERVICES"

    sput-object v0, Lcom/google/android/gms/internal/zzlr;->zzade:Ljava/lang/String;

    return-void
.end method

.method protected constructor <init>(Ljava/lang/String;Ljava/lang/Object;)V
    .registers 4
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "TT;)V"
        }
    .end annotation

    invoke-direct {p0}, Ljava/lang/Object;-><init>()V

    const/4 v0, 0x0

    iput-object v0, p0, Lcom/google/android/gms/internal/zzlr;->zzOX:Ljava/lang/Object;

    iput-object p1, p0, Lcom/google/android/gms/internal/zzlr;->zzue:Ljava/lang/String;

    iput-object p2, p0, Lcom/google/android/gms/internal/zzlr;->zzuf:Ljava/lang/Object;

    return-void
.end method

.method public static isInitialized()Z
    .registers 1

    sget-object v0, Lcom/google/android/gms/internal/zzlr;->zzadc:Lcom/google/android/gms/internal/zzlr$zza;

    if-eqz v0, :cond_6

    const/4 v0, 0x1

    :goto_5
    return v0

    :cond_6
    const/4 v0, 0x0

    goto :goto_5
.end method

.method public static zza(Ljava/lang/String;Ljava/lang/Float;)Lcom/google/android/gms/internal/zzlr;
    .registers 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "Ljava/lang/Float;",
            ")",
            "Lcom/google/android/gms/internal/zzlr",
            "<",
            "Ljava/lang/Float;",
            ">;"
        }
    .end annotation

    new-instance v0, Lcom/google/android/gms/internal/zzlr$4;

    invoke-direct {v0, p0, p1}, Lcom/google/android/gms/internal/zzlr$4;-><init>(Ljava/lang/String;Ljava/lang/Float;)V

    return-object v0
.end method

.method public static zza(Ljava/lang/String;Ljava/lang/Integer;)Lcom/google/android/gms/internal/zzlr;
    .registers 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "Ljava/lang/Integer;",
            ")",
            "Lcom/google/android/gms/internal/zzlr",
            "<",
            "Ljava/lang/Integer;",
            ">;"
        }
    .end annotation

    new-instance v0, Lcom/google/android/gms/internal/zzlr$3;

    invoke-direct {v0, p0, p1}, Lcom/google/android/gms/internal/zzlr$3;-><init>(Ljava/lang/String;Ljava/lang/Integer;)V

    return-object v0
.end method

.method public static zza(Ljava/lang/String;Ljava/lang/Long;)Lcom/google/android/gms/internal/zzlr;
    .registers 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "Ljava/lang/Long;",
            ")",
            "Lcom/google/android/gms/internal/zzlr",
            "<",
            "Ljava/lang/Long;",
            ">;"
        }
    .end annotation

    new-instance v0, Lcom/google/android/gms/internal/zzlr$2;

    invoke-direct {v0, p0, p1}, Lcom/google/android/gms/internal/zzlr$2;-><init>(Ljava/lang/String;Ljava/lang/Long;)V

    return-object v0
.end method

.method public static zzg(Ljava/lang/String;Z)Lcom/google/android/gms/internal/zzlr;
    .registers 4
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "Z)",
            "Lcom/google/android/gms/internal/zzlr",
            "<",
            "Ljava/lang/Boolean;",
            ">;"
        }
    .end annotation

    new-instance v0, Lcom/google/android/gms/internal/zzlr$1;

    invoke-static {p1}, Ljava/lang/Boolean;->valueOf(Z)Ljava/lang/Boolean;

    move-result-object v1

    invoke-direct {v0, p0, v1}, Lcom/google/android/gms/internal/zzlr$1;-><init>(Ljava/lang/String;Ljava/lang/Boolean;)V

    return-object v0
.end method

.method public static zzoo()I
    .registers 1

    sget v0, Lcom/google/android/gms/internal/zzlr;->zzadd:I

    return v0
.end method

.method static synthetic zzoq()Lcom/google/android/gms/internal/zzlr$zza;
    .registers 1

    sget-object v0, Lcom/google/android/gms/internal/zzlr;->zzadc:Lcom/google/android/gms/internal/zzlr$zza;

    return-object v0
.end method

.method public static zzu(Ljava/lang/String;Ljava/lang/String;)Lcom/google/android/gms/internal/zzlr;
    .registers 3
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            "Ljava/lang/String;",
            ")",
            "Lcom/google/android/gms/internal/zzlr",
            "<",
            "Ljava/lang/String;",
            ">;"
        }
    .end annotation

    new-instance v0, Lcom/google/android/gms/internal/zzlr$5;

    invoke-direct {v0, p0, p1}, Lcom/google/android/gms/internal/zzlr$5;-><init>(Ljava/lang/String;Ljava/lang/String;)V

    return-object v0
.end method

# virtual methods
.method public final get()Ljava/lang/Object;
    .registers 2
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TT;"
        }
    .end annotation

    iget-object v0, p0, Lcom/google/android/gms/internal/zzlr;->zzOX:Ljava/lang/Object;

    if-eqz v0, :cond_7

    iget-object v0, p0, Lcom/google/android/gms/internal/zzlr;->zzOX:Ljava/lang/Object;

    :goto_6
    return-object v0

    :cond_7
    iget-object v0, p0, Lcom/google/android/gms/internal/zzlr;->zzue:Ljava/lang/String;

    invoke-virtual {p0, v0}, Lcom/google/android/gms/internal/zzlr;->zzbY(Ljava/lang/String;)Ljava/lang/Object;

    move-result-object v0

    goto :goto_6
.end method

.method protected abstract zzbY(Ljava/lang/String;)Ljava/lang/Object;
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "(",
            "Ljava/lang/String;",
            ")TT;"
        }
    .end annotation
.end method

.method public final zzop()Ljava/lang/Object;
    .registers 4
    .annotation system Ldalvik/annotation/Signature;
        value = {
            "()TT;"
        }
    .end annotation

    invoke-static {}, Landroid/os/Binder;->clearCallingIdentity()J

    move-result-wide v0

    :try_start_4
    invoke-virtual {p0}, Lcom/google/android/gms/internal/zzlr;->get()Ljava/lang/Object;
    :try_end_7
    .catchall {:try_start_4 .. :try_end_7} :catchall_c

    move-result-object v2

    invoke-static {v0, v1}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    return-object v2

    :catchall_c
    move-exception v2

    invoke-static {v0, v1}, Landroid/os/Binder;->restoreCallingIdentity(J)V

    throw v2
.end method


text:
using System;
using System.Collections.Generic;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using DTcms.Common;

namespace DTcms.Web.admin.dialog
{
    public partial class dialog_check_cost_invoiced : Web.UI.ManagePage
    {
        private int id = 0;
        protected Model.CheckCost model = new Model.CheckCost();

        protected void Page_Load(object sender, EventArgs e)
        {
            id = DTRequest.GetQueryInt("id");
            if (id < 1)
            {
                JscriptMsg("传输参数不正确!", "back");
                return;
            }
            if (!new BLL.CheckCost().ExistsById(id))
            {
                JscriptMsg("数据不存在或已被删除!", "back");
                return;
            }
            if (!Page.IsPostBack)
            {
                ShowInfo(id);
            }
        }

        #region 赋值操作=================================
        private void ShowInfo(int _id)
        {
            BLL.CheckCost bll = new BLL.CheckCost();
            model = bll.GetModelById(_id);
        }
        #endregion
    }
}


text:
import argparse
import logging
import sys

import pystradamus

def main():
    """Sets up the main config parser for the main entry point, this does common
    things like print help or the version and then dispatches to further down
    sub-parsers for specific information
    """
    # configure logging to just go to stdout
    logging.basicConfig(
        format="%(asctime)s [%(levelname)-10s] (%(name)s) %(message)s",
        stream=sys.stdout,
        level=logging.INFO
    )

    log = logging.getLogger(__name__)

    # build the main parser
    main_parser = argparse.ArgumentParser()
    main_parser.add_argument('-c', '--config', metavar="FILE",
            type=argparse.FileType('r'), help="path to config file")
    main_parser.add_argument('-v', '--verbose', help="show debug messages",
            action='store_true')
    main_parser.add_argument('-d', '--database', metavar="FILE",
            help="path to the sqllite3 database file to use",
            default='evidence.db')
    main_parser.add_argument('--version', help='print version and exit')
    subparsers = main_parser.add_subparsers()

    #history functionality
    history_parser = subparsers.add_parser('history', help='history yo')
    history_parser.add_argument('-r', '--refresh', help="Pulls historic ticket "
            "data from jira", action="store_true")
    history_parser.add_argument('-p', '--predict', help="Generate a probability"
            " curve for the next assigned ticket with an estimate for a given "
            "user", action="store_true")
    history_parser.add_argument('username', type=str,
            help='JIRA username to query tickets for')
    history_parser.set_defaults(func=pystradamus.history.main)

    config_parser = subparsers.add_parser('config', help='config yo')
    config_parser.add_argument('-f', '--fields', action="store_true",
            help="Pulls custom fields and their ids from Jira")
    config_parser.set_defaults(func=pystradamus.config.main)

    # parse args and dispatch to the correct handler
    args = main_parser.parse_args()
    cfg = pystradamus.config.locate_and_parse(args.config)
    if cfg is None and args.func is not pystradamus.config.main:
        pystradamus.utils.error_exit("No configuration found!")
    args.cfg = cfg
    if args.verbose:
        logging.getLogger().setLevel(logging.DEBUG)

    pystradamus.storage.init(args.database)
    args.func(args)


text:
<?php

namespace app\models;

use Yii;
use yii\base\Model;
use yii\data\ActiveDataProvider;
use app\models\Receta;

/**
 * RecetaSearch represents the model behind the search form about `app\models\Receta`.
 */
class RecetaSearch extends Receta
{
    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['id_receta'], 'integer'],
            [['nombre_receta'], 'safe'],
        ];
    }

    /**
     * @inheritdoc
     */
    public function scenarios()
    {
        // bypass scenarios() implementation in the parent class
        return Model::scenarios();
    }

    /**
     * Creates data provider instance with search query applied
     *
     * @param array $params
     *
     * @return ActiveDataProvider
     */
    public function search($params)
    {
        $query = Receta::find();

        $dataProvider = new ActiveDataProvider([
            'query' => $query,
        ]);

        $this->load($params);

        if (!$this->validate()) {
            // uncomment the following line if you do not want to return any records when validation fails
            // $query->where('0=1');
            return $dataProvider;
        }

        $query->andFilterWhere([
            'id_receta' => $this->id_receta,
        ]);

        $query->andFilterWhere(['like', 'nombre_receta', $this->nombre_receta]);

        return $dataProvider;
    }
}


text:
import React from 'react';
import _ from 'lodash';
import {connect} from 'react-redux';
import Loader from "../../../../loaders/diamond/loader";
import Options from "./options";

const DungeonRun = ({classChallenge, loading, allCards}) =>{
  if(!loading) {
    let updatedCards;
    let cards = [];
    let card = classChallenge.options.map(option => {
      const {label, icon, cards} = option;
      const card = cards.map(card => allCards.find(c => card === c.name));
      return {label, icon, cards: card}
    });
    updatedCards = _.concat(card, cards);

    return <Options options={updatedCards}/>;
  }
  return (

<Loader/>

  )
};

const mapStateToProps = state =>{
  const {cards} = state.cards;
  const {loading, allCards} = cards;
  return {loading, allCards}
};

export default connect(mapStateToProps, null)(DungeonRun);


text:
This blog uses a different approach, instead of storing the post
on a database, the post are store on the same git repository.

# Blog Application
The blog application is developed under React framework

# Git Project
Current the post are located undet the git project.


text:
<resources>
    <string name="app_name">Probe Android</string>
</resources>