text:
<?php

namespace ZendTest\Log\Filter;

use Zend\Log\Filter\Sample;

/**
 * @category   Zend
 * @package    Zend_Log
 * @subpackage UnitTests
 * @group      Zend_Log
 */
class SampleTest extends \PHPUnit_Framework_TestCase
{
    public function testConstructorThrowsOnInvalidSampleRate()
    {
        $this->setExpectedException('Zend\Log\Exception\InvalidArgumentException', 'must be numeric');
        new Sample('bar');
    }

    public function testSampleLimit0()
    {
        // Should log nothing.
        $filter = new Sample(0);

        // Since sampling is a random process, let's test several times.
        $ret = false;
        for ($i = 0; $i < 100; $i ++) {
            if ($filter->filter(array())) {
                break;
                $ret = true;
            }
        }

        $this->assertFalse($ret);
    }

    public function testSampleLimit1()
    {
        // Should log all events.
        $filter = new Sample(1);

        // Since sampling is a random process, let's test several times.
        $ret = true;
        for ($i = 0; $i < 100; $i ++) {
            if (! $filter->filter(array())) {
                break;
                $ret = false;
            }
        }

        $this->assertTrue($ret);
    }
}


text:
enum EngineMessageType {
	MESSAGE_TYPE_UNSPECIFIED,
	//
	MESSAGE_TYPE_FRAME_EVENT,
	MESSAGE_TYPE_FIFTH_FRAME_EVENT,
	MESSAGE_TYPE_TENTH_FRAME_EVENT,
	MESSAGE_TYPE_500_MS_TIME_EVENT,
	MESSAGE_TYPE_5_S_TIME_EVENT,
	//
	MESSAGE_TYPE_SCENE_START,
	MESSAGE_TYPE_SCENE_END,
	//
	MESSAGE_TYPE_TRANSFORM_CHANGED_EVENT,
	//
	MESSAGE_TYPE_DIRECTIONAL_LIGHT_CHANGED,
	MESSAGE_TYPE_CAMERA_CHANGED,
	//
	MESSAGE_TYPE_ANIMATION_BEGAN_EVENT,
	MESSAGE_TYPE_ANIMATION_PAUSED_EVENT,
	MESSAGE_TYPE_ANIMATION_RESUMED_EVENT,
	MESSAGE_TYPE_ANIMATION_ENDED_EVENT,
	//
	MESSAGE_TYPE_PINCH_GESTURE,
	MESSAGE_TYPE_LONG_PRESS_GESTURE,
	//
	MESSAGE_TYPE_PARTICLE_SYSTEM_INITED,
	MESSAGE_TYPE_PARTICLE_SYSTEM_UPDATED,
	//
	MESSAGE_TYPE_PARTICLE_SYSTEM_SPENT,
	//
	// MUST BE LAST
	NUM_ENGINE_MESSAGE_TYPES,
};

enum MessageDataType {
	MESSAGEDATA_TYPE_GENERIC_EMPTY_MESSAGE,
	MESSAGEDATA_TYPE_1S_1I_3FV,				// Generic carrier for 1 string, 1 int, and 3 vec3<float>s
	MESSAGEDATA_TYPE_1S_1I_1F,				// Generic carrier for 1 string, 1 int, and 1 float
};

#endif // MESSAGEHUB_DECLARATIONS_H

redpajama_set_name: RedPajamaGithub


text:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Frameset//EN""http://www.w3.org/TR/REC-html40/frameset.dtd">

<TITLE>
JDOM v1.0: Class  JDOMSource
</TITLE>
<LINK REL ="stylesheet" TYPE="text/css" HREF="../../../stylesheet.css" TITLE="Style">

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JDOM
1.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

org.jdom.transform

Class  JDOMSource

java.lang.Object
  |
  +--javax.xml.transform.sax.SAXSource
        |
        +--org.jdom.transform.JDOMSource

public class JDOMSource
extends javax.xml.transform.sax.SAXSource

A holder for an XML Transformation source: a Document, Element, or list of
 nodes.

 The is provides input to a
 JAXP TrAX Transformer.

 The following example shows how to apply an XSL Transformation
 to a JDOM document and get the transformation result in the form
 of a list of JDOM nodes:

   public static List transform(Document doc, String stylesheet)
                                        throws JDOMException {
     try {
       Transformer transformer = TransformerFactory.newInstance()
                             .newTransformer(new StreamSource(stylesheet));
       JDOMSource in = new JDOMSource(doc);
       JDOMResult out = new JDOMResult();
       transformer.transform(in, out);
       return out.getResult();
     }
     catch (TransformerException e) {
       throw new JDOMException("XSLT Transformation failed", e);
     }
   }

Version:
$Revision: 1.18 $, $Date: 2004/08/31 04:43:48 $

Author:
Laurent Bihanic, Jason Hunter

See Also:
JDOMResult

Field Summary

static java.lang.String
JDOM_FEATURE

          If javax.xml.transform.TransformerFactory#getFeature
 returns true when passed this value as an
 argument, the Transformer natively supports JDOM.

Fields inherited from class javax.xml.transform.sax.SAXSource

FEATURE

Constructor Summary

JDOMSource(Document source)

          Creates a JDOM TrAX source wrapping a JDOM document.

JDOMSource(Element source)

          Creates a JDOM TrAX source wrapping a JDOM element.

JDOMSource(java.util.List source)

          Creates a JDOM TrAX source wrapping a list of JDOM nodes.

Method Summary

 Document
getDocument()

          Returns the source document used by this TrAX source.

 java.util.List
getNodes()

          Returns the source node list used by this TrAX source.

 org.xml.sax.XMLReader
getXMLReader()

          Returns the XMLReader to be used for the Source.

 void
setDocument(Document source)

          Sets the source document used by this TrAX source.

 void
setInputSource(org.xml.sax.InputSource inputSource)

          Sets the SAX InputSource to be used for the Source.

 void
setNodes(java.util.List source)

          Sets the source node list used by this TrAX source.

 void
setXMLReader(org.xml.sax.XMLReader reader)

          Set the XMLReader to be used for the Source.

Methods inherited from class javax.xml.transform.sax.SAXSource

getInputSource,
getSystemId,
setSystemId,
sourceToInputSource

Methods inherited from class java.lang.Object

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

Field Detail

JDOM_FEATURE

public static final java.lang.String JDOM_FEATURE

If javax.xml.transform.TransformerFactory#getFeature
 returns true when passed this value as an
 argument, the Transformer natively supports JDOM.

 Note: This implementation does not override
 the SAXSource.FEATURE value defined by its superclass
 to be considered as a SAXSource by Transformer implementations
 not natively supporting JDOM.

Constructor Detail

JDOMSource

public JDOMSource(Document source)

Creates a JDOM TrAX source wrapping a JDOM document.

Parameters:
source - the JDOM document to use as source for the
                  transformations
Throws:
java.lang.IllegalArgumentException - if source is
                                    null.

JDOMSource

public JDOMSource(java.util.List source)

Creates a JDOM TrAX source wrapping a list of JDOM nodes.

Parameters:
source - the JDOM nodes to use as source for the
                  transformations
Throws:
java.lang.IllegalArgumentException - if source is
                                    null.

JDOMSource

public JDOMSource(Element source)

Creates a JDOM TrAX source wrapping a JDOM element.

Parameters:
source - the JDOM element to use as source for the
                  transformations
Throws:
java.lang.IllegalArgumentException - if source is
                                    null.

Method Detail

setDocument

public void setDocument(Document source)

Sets the source document used by this TrAX source.

Parameters:
source - the JDOM document to use as source for the
                  transformations
Throws:
java.lang.IllegalArgumentException - if source is
                                    null.
See Also:
getDocument()

getDocument

public Document getDocument()

Returns the source document used by this TrAX source.

Returns:
the source document used by this TrAX source or
         null if the source is a node list.
See Also:
setDocument(org.jdom.Document)

setNodes

public void setNodes(java.util.List source)

Sets the source node list used by this TrAX source.

Parameters:
source - the JDOM nodes to use as source for the
                  transformations
Throws:
java.lang.IllegalArgumentException - if source is
                                    null.
See Also:
getNodes()

getNodes

public java.util.List getNodes()

Returns the source node list used by this TrAX source.

Returns:
the source node list used by this TrAX source or
         null if the source is a JDOM document.
See Also:
setDocument(org.jdom.Document)

setInputSource

public void setInputSource(org.xml.sax.InputSource inputSource)
                    throws java.lang.UnsupportedOperationException

Sets the SAX InputSource to be used for the Source.

 As this implementation only supports JDOM document as data
 source, this method always throws an
 UnsupportedOperationException.

Overrides:
setInputSource in class javax.xml.transform.sax.SAXSource

Parameters:
inputSource - a valid InputSource reference.
Throws:
java.lang.UnsupportedOperationException - always!

setXMLReader

public void setXMLReader(org.xml.sax.XMLReader reader)
                  throws java.lang.UnsupportedOperationException

Set the XMLReader to be used for the Source.

 As this implementation only supports JDOM document as data
 source, this method throws an
 UnsupportedOperationException if the provided reader
 object does not implement the SAX XMLFilter
 interface.  Otherwise, the JDOM document reader will be
 attached as parent of the filter chain.

Overrides:
setXMLReader in class javax.xml.transform.sax.SAXSource

Parameters:
reader - a valid XMLReader or XMLFilter reference.
Throws:
java.lang.UnsupportedOperationException - if reader
                                         is not a SAX
                                         XMLFilter.
See Also:
getXMLReader()

getXMLReader

public org.xml.sax.XMLReader getXMLReader()

Returns the XMLReader to be used for the Source.

 This implementation returns a specific XMLReader reading
 the XML data from the source JDOM document.

Overrides:
getXMLReader in class javax.xml.transform.sax.SAXSource

Returns:
an XMLReader reading the XML data from the source
         JDOM document.

      Overview
      Package
    Class
      Use
      Tree
      Deprecated
      Index
      Help

JDOM
1.0

 PREV CLASS
 NEXT CLASS

  FRAMES
 NO FRAMES

  SUMMARY:  INNER | FIELD | CONSTR | METHOD

DETAIL:  FIELD | CONSTR | METHOD

Copyright © 2004 Jason Hunter, Brett McLaughlin. All Rights Reserved.


text:
Usage
=====

This is a very small example on how to build a simple MongoRest API.

Project Settings
----------------

To define the settings for your project you should set the environment variable
`MONGOREST_SETTINGS_MODULE` to the module where the settings are stored::

    from os import environ
    environ['MONGOREST_SETTINGS_MODULE'] = 'project.settings'

Database
--------

To connect to your database you should specify the `MONGODB` setting on your
mongorest settings module. You can set the connection `URI`, or use other
options like setting the `HOSTS` and `PORTS` of your replica-set.
If you are not using a replica-set you can just set the one `HOST` and `PORT`::

    MONGODB = {
        'URI': '',
        'USERNAME': '',
        'PASSWORD': '',
        'HOST': 'localhost'
        'HOSTS': [],
        'PORT': 27017
        'PORTS': [],
        'DATABASE': 'mongorest',
        'OPTIONS': [],
    }

Example
-------

Here is a basic example of how easy it is to create an example library API with **MongoRest**::

    from mongorest.collection import Collection

    class Book(Collection):
        schema = {
            'name': {'type': 'string', 'required': True},
            'genre': {'type': 'string', 'required': True},
            'author': {'type': 'string', 'required': True},
            'number_of_pages': {'type': 'integer'},
            'release_date': {'type': 'datetime'},
        }

First we created our Book collection that inherited from the `mongorest.Collection` class,
then we added a `schema` to specify the fields, and their types.
For more details on schema creation visit the `Cerberus documentation <http://cerberus.readthedocs.io/>`_::

    from mongorest.resource import (
        ListResourceMixin, CreateResourceMixin
    )

    class BookResource(ListResourceMixin, CreateResourceMixin):
        collection = Book
        endpoint = 'books'

Here, by inheriting from these mongorest-builtin Mixins, our resource already has the list and create actions.
We also defined what will be the collection and endpoint this Resource refers to::

    from mongorest.wsgi import WSGIDispatcher
    from werkzeug.serving import run_simple

    if __name__ == '__main__':
        wsgi_app = WSGIDispatcher([BookResource])
        run_simple('localhost', 8000, wsgi_app)

Now we just had to instantiate the application as a `WSGIDispatcher` passing it our list of resources.
After that, we started our server and the API is ready to be consumed.


text:
/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/include/usr/hwas/common/deconfigGard.H $                  */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2012,2015                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
/**
 *  @file deconfigGard.H
 *
 *  @brief Defines the DeconfigGard class that provides functions to deconfigure
 *  and create GARD records for Targets
 */

#ifndef DECONFIGGARD_H_
#define DECONFIGGARD_H_

#include <vector>
#include <hwas/common/hwasCommon.H>
#include <hwas/common/hwasCallout.H>
#include <targeting/common/attributes.H>
#include <hwas/hwasPlatDeconfigGard.H>
#include <hwas/hwasPlatThread.H>

#include <targeting/common/commontargeting.H>

class HwasGardTest;

namespace HWAS
{

/**
 * @brief   collectGard   Common HWAS function to collect the GARD info
 *
 *  It will call into hwas platform-specific functions.
 *
 * @param  i_pPredicate     restrict processing - only look at GARD records
 *                          for targets that match the predicate (optional)
 *
 * @return errlHndl_t       valid errlHndl_t handle if there was an error
 *                          NULL if no errors;
 */
errlHndl_t collectGard(const TARGETING::PredicateBase *i_pPredicate = NULL);

/**
 * @brief Returns a reference to the DeconfigGard singleton.
 */
class DeconfigGard;
DeconfigGard & theDeconfigGard();

/**
 * @class DeconfigGard
 *
 * This class defines the singleton that handles Deconfigure and GARD Record
 * functionality
 */
class DeconfigGard
{

    // Allow HwasGardTest to access private methods.
    friend class ::HwasGardTest;

public:

    // enums for events codes for Gard events
    // used by platLogEvent() function
    enum GardEvent
    {                       // if GARD record:
        GARD_APPLIED,       //  applied
        MFG,                //  not applied due to MFG policy
        PREDICTIVE,         //  not applied due to predictive policy
        PREDICATE,          //  not applied due to predicate
        GARD_NOT_APPLIED,   //  not applied for other reason
        RESOURCE_RECOVERED  //  Resource recovered
    };

    // enums to indicate to deconfigureTarget() specific behaviors
    enum DeconfigureFlags
    {
        NOT_AT_RUNTIME,     // non-runtime behavior - if the system is at
                            // runtime, no deconfigs happen;

                            // runtime behaviors:
        FULLY_AT_RUNTIME,   // - functional=false,dumpfunctional=false
        DUMP_AT_RUNTIME,    // - functional=false,dumpfunctional=true
        SPEC_DECONFIG,      //speculative deconfig
    };

    // enums to indicate non-error reason for a targets deconfiguration.
    //  used in TARGETING::HwasSate.deconfiguredByEid
    enum DeconfiguredByReason
    {
        DECONFIGURED_BY_CODE_BASE               = 0x0000FF00,

        // set when GARD_User_Manual
        DECONFIGURED_BY_MANUAL_GARD,            // BASE | 0x01

        // set by processFieldCoreOverride() in hwas/common/deconfigGard.C
        DECONFIGURED_BY_FIELD_CORE_OVERRIDE,    // BASE | 0x02

        // set by call_mss_getecid() in dmi_training.c
        DECONFIGURED_BY_MEMORY_CONFIG,          // BASE | 0x03

        // set by presentByAssoc() when a MCS has no MEMBUFs
        DECONFIGURED_BY_NO_CHILD_MEMBUF,        // BASE | 0x04

        // set by deconfigureAssocProc() in hwas/common/deconfigGard.C
        DECONFIGURED_BY_BUS_DECONFIG,           // BASE | 0x05

        // set by prd code, deconfigures at runtime
        DECONFIGURED_BY_PRD,                    // BASE | 0x06

        // set for PHYP initiated deconfigure
        DECONFIGURED_BY_PHYP,                   // BASE | 0x07

        // set for SPCN initiated deconfigure
        DECONFIGURED_BY_SPCN,                   // BASE | 0x08

        // set by presentByAssoc() when a MBA has no MEMBUF
        DECONFIGURED_BY_NO_PARENT_MEMBUF,       // BASE | 0x09

        // set by presentByAssoc() when a MBA has no DIMMs
        DECONFIGURED_BY_NO_CHILD_DIMM,          // BASE | 0x0A

        // set by presentByAssoc() when a MEMBUF has no MCS
        DECONFIGURED_BY_NO_PARENT_MCS,          // BASE | 0x0B

        // set by presentByAssoc() when a MEMBUF has no MBAs
        DECONFIGURED_BY_NO_CHILD_MBA,           // BASE | 0x0C

        // set by presentByAssoc() when a DIMM has no MBA
        DECONFIGURED_BY_NO_PARENT_MBA,          // BASE | 0x0D

        CONFIGURED_BY_RESOURCE_RECOVERY,        // BASE | 0x0E

        // mask - these bits mean it's a PLID and not an enum
        DECONFIGURED_BY_PLID_MASK                = 0xFFFF0000,
    };

    /**
     * @struct GardRecord
     *
     * Defines a GARD Record.
     *
     * Multiple GARD Records can exist for a specific Target
     */
    struct GardRecord
    {
        uint32_t              iv_recordId;
        TARGETING::EntityPath iv_targetId;
        uint32_t              iv_errlogEid;
        uint8_t               iv_errorType; //from hwasCallout.H GARD_ErrorType
        uint8_t               iv_ResourceRecovery;
        uint8_t               iv_padding[6];
    };

    typedef std::vector<GardRecord> GardRecords_t;
    typedef std::vector<GardRecord>::iterator GardRecordsItr_t;
    typedef std::vector<GardRecord>::const_iterator GardRecordsCItr_t;
    typedef struct GardRecord GardRecord;
    /**
     * @struct DeconfigureRecord
     *
     * Defines a Deconfigure Record for deferred deconfigures
     *
     * Only one Deconfigure Record can exist for a specific Target
     */
    struct DeconfigureRecord
    {
        const TARGETING::Target * iv_target;
        uint32_t            iv_errlogEid; // plid OR deconfigReason value
    };

    typedef std::vector<DeconfigureRecord> DeconfigureRecords_t;
    typedef std::vector<DeconfigureRecord>::iterator DeconfigureRecordsItr_t;
    typedef std::vector<DeconfigureRecord>::const_iterator DeconfigureRecordsCItr_t;

    /**
     * @brief Destructor.
     */
    ~DeconfigGard();

    /**
     * @brief Apply gard record for a specific target.
     *
     * Called by deconfigureTargetsFromGardRecordsForIpl.
     *
     * @param i_pTarget Target to be garded
     *
     * @param i_gardRecord gard record to be applied
     *
     * @param i_deconfigRule Options for deconfigure
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t applyGardRecord(TARGETING::Target *i_pTarget,
            GardRecord &i_gardRecord,
            const DeconfigureFlags i_deconfigRule =  NOT_AT_RUNTIME);

    /**
     * @brief Clears GARD Records for replaced Targets.
     *
     * Called by HWAS as part of initial IPL steps.
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t clearGardRecordsForReplacedTargets();

    /**
     * @brief Deconfigures Targets that have GARD Records in preparation to IPL.
     *
     * @param  i_pPredicate     restrict processing - only look at GARD records
     *                          for targets that match the predicate (optional)
     *
     * Called by HWAS as part of initial IPL steps.
     *
     * If deconfiguring all such Targets will result in a configuration that is
     * unable to IPL then it figures out which subset of Targets to deconfigure
     * to give the best chance of IPL (Resource Recovery).
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t deconfigureTargetsFromGardRecordsForIpl(
                const TARGETING::PredicateBase *i_pPredicate = NULL);
    /**
     * @brief Re-log the PEL which caused the input Gard event
     *
     * @param  i_gardRecord    Reference to the Gard Record which will be
     *                         re-logged
     *
     * Called by HWAS common as part of the deconfigure targets from Gard
     * Records for IPL. Caller must pass distinct Gard PEL.
     *
     * @return errlHndl_t. Error log Handle
     * */
     errlHndl_t platReLogGardError(GardRecord &i_gardRecord);
    /**
     * @brief Processes the Field Core Override attribute
     *
     * Called by HWAS as part of initial IPL steps.
     *
     * if the Field Core Override is non-zero, then functional cores will
     * be made non-functional, until the number of functional cores is equal
     * to the FCO value;
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t processFieldCoreOverride();

    /**
     * @brief Deconfigures a Target.
     *
     * Called from processCallout, which is called
     * by ErrlManager when committing an error log containing a
     * Deconfigure request.
     *
     * This will Deconfigure the Target (set state to non-functional, do any
     * Deconfigure actions and create a Deconfigure Record) and Deconfigure
     * Targets by association. Any errors deconfiguring targets are committed
     * and the function continues. The only errors returned are usage errors.
     * By default, targets are NOT deconfigured if the system is at Runtime.
     *
     * @param[in]  i_target   Reference to Target to deconfigure.
     * @param[in]  i_errlEid Error log EID to store in Deconfigure Record.
     * @param[out] o_targetDeconfigured - if pointer is valid, bool is set
     *                  to true if target was deconfigured; NOT SET OTHERWISE
     * @param[in]  i_deconfigRule Deconfigure options -
     *              default not at runtime
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t deconfigureTarget(TARGETING::Target & i_target,
                           const uint32_t i_errlEid,
                           bool *o_targetDeconfigured = NULL,
                           const DeconfigureFlags i_deconfigRule =
                                    NOT_AT_RUNTIME);

    /**
     * @brief Registers a Deferred Deconfigure
     *
     * Called from errludcallout, which is called
     * by hwasCallout when the user requests a
     * Deferred Deconfigure request.
     *
     * Create a deconfigure record, which will be handled in the function
     * processDeferredDeconfig().
     *
     * @param[in] i_target   Reference to Target to deconfigure.
     * @param[in] i_errlEid Error log EID to store in Deconfigure Record.
     *
     */
    void registerDeferredDeconfigure(const TARGETING::Target & i_target,
                                 const uint32_t i_errlEid);

    /**
     * @brief Platform specific function that
     *          logs a special trace event
     *
     * @param[in] i_pTarget  Pointer to Target
     * @param[in] i_eventType GardEvent enum
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t platLogEvent(const TARGETING::Target * const i_pTarget,
                                const GardEvent i_eventType);

    /**
     * @brief Platform specific function that
     *          Creates a GARD Record for a Target.
     *
     * @param[in] i_pTarget  Pointer to Target to create GARD Record for.
     * @param[in] i_errlEid Error log EID to store in GARD Record.
     * @param[in] i_errorType error type of the GARD Record.
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t platCreateGardRecord(const TARGETING::Target * const i_pTarget,
                                const uint32_t i_errlEid,
                                const GARD_ErrorType i_errorType);

    /**
     * @brief Clears GARD Record for the specified Target, or ALL GARD
     *          records.
     *
     * Called by an administrator to clear GARD records manually.
     *
     * If no GARD Records exist for the Target then no error is returned. The
     * only errors returned are usage errors and errors accessing the GARD
     * Records.
     *
     * @param[in] i_pTarget Pointer to Target to clear GARD record for.
     *              If NULL, then ALL GARD Records will be cleared.
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t clearGardRecords(const TARGETING::Target * const i_pTarget);

    /**
     * @brief Platform specific function that
     *          Clears Record for the specified Target.
     *
     * @param[in] i_pTarget Pointer to Target to clear GARD record for.
     *              If NULL, then ALL GARD Records will be cleared.
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t platClearGardRecords(const TARGETING::Target * const i_pTarget);

    /**
     * @brief Gets all GARD Records for the specified Target.
     *
     * Called by an administrator to view GARD Records.
     *
     * If no GARD Records exist for the Target then no error is returned. The
     * only errors returned are usage errors and errors accessing the GARD
     * Records.
     *
     * @param[in]  i_pTarget  Pointer to Sys or Node Target
     * @param[out] o_records  Reference to vector of GardRecords that is cleared
     *                        then filled in with records.
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t getGardRecords(const TARGETING::Target * const i_pTarget,
                              GardRecords_t & o_records);

    /**
     * @brief Platform specific function that
     *          Gets all GARD Records for the specified Target.
     *
     * @param[in]  i_pTarget  Pointer to Sys or Node Target
     * @param[out] o_records  Reference to vector of GardRecords that is cleared
     *                        then filled in with records.
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t platGetGardRecords(const TARGETING::Target * const i_pTarget,
                              GardRecords_t & o_records);

protected:

    /**
     * @brief Default constructor
     *
     * Can only be called by Singleton
     */
    DeconfigGard();

private:

    // Copy constructor and assignment operator disabled
    DeconfigGard(const DeconfigGard & i_right);
    DeconfigGard & operator=(const DeconfigGard & i_right);

    /**
     * @brief Maximum number of A/X bus endpoints. Used to initialize
     *        ProcInfo structs.
     */
    static const uint8_t NUM_A_BUSES = 3; // Max number of ABus links
    static const uint8_t NUM_X_BUSES = 4; // Max number of XBus links

    /**
     * @brief  Struct representing a particular processor.  Used by
     * _invokeDeconfigureAssocProc to populate a vector of procInfo's
     * effectively describing the current system state for subsequent use by
     * _deconfigureAssocProc
     */
    struct ProcInfo
    {
        // target for this chip
        TARGETING::Target * iv_pThisProc;
        TARGETING::ATTR_HUID_type procHUID;
        TARGETING::ATTR_FABRIC_NODE_ID_type procFabricNode;
        TARGETING::ATTR_FABRIC_CHIP_ID_type procFabricChip;
        bool iv_masterCapable;
        bool iv_deconfigured;

        // targets defining A link connected chips
        ProcInfo * iv_pAProcs[NUM_A_BUSES];
        bool iv_ADeconfigured[NUM_A_BUSES];

        // targets defining X link connected chips
        ProcInfo * iv_pXProcs[NUM_X_BUSES];
        bool iv_XDeconfigured[NUM_X_BUSES];
    };

    // Structure populated in _invokeDeconfigureAssocProc() for use in
    // _deconfigureAssocProc()
    typedef std::vector<ProcInfo> ProcInfoVector;

    /**
     * @brief Deconfigures Targets by association.
     *
     * @param[in] i_target   Reference to base Target.
     * @param[in] i_errlEid Error log EID to store in Deconfigure Record.
     * @param[in] i_deconfigRule Deconfigure Runtime options -
     *              default not at runtime
     */
    void _deconfigureByAssoc(TARGETING::Target & i_target,
                             const uint32_t i_errlEid,
                             const DeconfigureFlags i_deconfigRule =
                                    NOT_AT_RUNTIME);

    /**
     * @brief Deconfigures a Target.
     *
     * This will Deconfigure the Target (set state to non-functional, do any
     * Deconfigure actions and create a Deconfigure Record).
     *
     * @param[in] i_target   Reference to Target to deconfigure.
     * @param[in] i_errlEid Error log EID to store in Deconfigure Record.
     * @param[out] o_targetDeconfigured - if pointer is valid, bool is set
     *                  to true if target was deconfigured; NOT SET OTHERWISE
     * @param[in] i_deconfigRule Deconfigure Runtime options -
     *              default not at runtime
     */
    void _deconfigureTarget(TARGETING::Target & i_target,
                            const uint32_t i_errlEid,
                            bool *o_targetDeconfigured = NULL,
                            const DeconfigureFlags i_deconfigRule =
                                    NOT_AT_RUNTIME);

    /**
     * @brief Performs Deconfigure Actions.
     *
     * @param[in] i_target Reference to Target to perform actions on.
     */
    void _doDeconfigureActions(TARGETING::Target & i_target);

    /**
     * @brief Creates a Deconfigure Record
     *
     * @param[in] i_target   Reference to Target to create record for.
     * @param[in] i_errlEid Error log EID to store in Deconfigure Record.
     */
    void _createDeconfigureRecord(const TARGETING::Target & i_target,
                                  const uint32_t i_errlEid);

    /**
     *  @brief Invokes _deconfigureAssocProc
     *
     *  Called by deconfigureAssocProc and
     *  deconfigureTargetsFromGardRecordsForIpl. This function queries the
     *  system and populates a vector of structs which represent
     *  processors.  This vector is then passed to _deconfigureAssocProc
     *  which systematically marks processors to be deconfigured based
     *  on previously deconfigured bus endpoint chiplets.  Upon
     *  completion of _deconfigureAssocProc, this function iterates
     *  through the returned vector and deconfigures any proc marked
     *  for deconfiguration.
     *
     *  @param[in] i_node           restrict processing - only apply algorithm
     *                              to targets that match the predicate
     *  @param[in] i_doAbusDeconfig indicates if abus logic should be considered
     *
     *  @return errlHndl_t. Error log handle.
     *
     */
    errlHndl_t _invokeDeconfigureAssocProc(
                TARGETING::ConstTargetHandle_t i_node = NULL,
                bool i_doAbusDeconfig = true);

    /**
     *  @brief _deconfigureAssocProc deconfigures procs based on
     *         deconfigured x/a buses.
     *
     *  Run once per logical node, this algorithm systematically
     *  marks processors, by setting deconfigured booleans in a
     *  vector of structs which represent the processors, for
     *  deconfiguration based on previously deconfigured bus endpoint
     *  chiplets. Upon completion, this function then calls
     *  _symmetryValidation to ensure all logical nodes are symmetric
     *  from an available processor standpoint.
     *
     *  @param[in/out]  io_procInfo  Reference to vector of ProcInfo struct
     *                               pointers which contain the pertinant
     *                               information about a particular processor
     *
     *  @return errlHndl_t. Error log handle.
     *
     */
    static errlHndl_t _deconfigureAssocProc(ProcInfoVector &io_procInfo);

    /**
     *  @brief Performs SMP node balancing
     *
     *  Called by _deconfigureAssocProc.
     *  This function examines a vector of structs representing
     *  processors, and systematically marks processors to be
     *  deconfigured based on the state of the master-proc-containing
     *  logical node to ensure symmetry from an available processor
     *  standpoint.
     *
     *  @param[in/out]  io_procInfo  Reference to vector of ProcInfo struct
     *                               pointers which contain the pertinant
     *                               information about a particular processor
     *
     *
     *  @return errlHndl_t. Error log handle.
     *
     */
    static errlHndl_t _symmetryValidation(ProcInfoVector &io_procInfo);

    /**
     *  @brief Clear all Deconfigure due to Field Core Override
     *
     *  Called by processFieldCoreOverride.
     *  This function clears the deconfiguration based on
     *  field core override and prepare for applying filed core override
     *  again.
     *
     *  @param[in]  i_nodeTarget Node which FCO to be cleared.
     *
     *  @return errlHndl_t. Error log handle.
     *
     */
    static void _clearFCODeconfigure(
                TARGETING::ConstTargetHandle_t i_nodeTarget);

public:

    /**
     * @brief Gets the specified Deconfigure Records.
     *
     * Called by an administrator to view Deconfigure Records. There can only be
     * one Deconfiguration Record per Target.
     *
     * If the specified record does not exist then no error is returned. The
     * only errors returned are usage errors and errors accessing the
     * Deconfigure Records.
     *
     * @note Provided for unit test only. Production code should not be
     *       clearing Deconfigure Records.
     *
     * @param[in]  i_pTargetId Pointer to the Target ID to get the Deconfigure
     *                         Record for. If NULL then all Deconfigure Records
     *                         are retrieved.
     * @param[out] o_records   Reference to vector of DeconfigureRecords that is
     *                         cleared then filled in with records.
     *
     * @return errlHndl_t. Error log handle.
     */
    errlHndl_t _getDeconfigureRecords(const TARGETING::Target * const i_pTarget,
                                     DeconfigureRecords_t & o_records);

    /**
     * @brief Clears the specified Deconfigure Records.
     *
     * @param[in] i_pTargetId Pointer to the Target ID to clear Deconfigure
     *                        Records for. If NULL then all Deconfigure Records
     *                        are cleared.
     */
    void clearDeconfigureRecords(const TARGETING::Target * const i_pTarget);

    /**
     *  @brief processDeferredDeconfig process any deferred deconfigure
     *              callouts that might have been 'queued' up.
     *              This is called from the istep dispatcher
     */
    void processDeferredDeconfig();

    /**
     *  @brief Starts deconfiguration of procs based on deconfigured
     *  bus endpoints process
     *
     *  Called by call_host_startprd_pbus (istep 8.6).  This function
     *  calls _invokeDeconfigureAssocProc to begin the calculated
     *  deconfiguration of processors based on previously deconfigured
     *  bus endpoint chiplets.
     *
     *  @return errlHndl_t. Error log handle.
     *
     */
    errlHndl_t deconfigureAssocProc();

    /**
     *  @brief Sets iv_XABusEndpointDeconfigured
     *
     *  @param[in] deconfig Allows iv_XABusEndpointDeconfigured to be set
     *                      to true/false
     *
     */
    void setXABusEndpointDeconfigured(bool deconfig);

private:

    // Mutex for thread safety
    HWAS_MUTEX_TYPE iv_mutex;

    // The Deconfigure Records
    DeconfigureRecords_t iv_deconfigureRecords;

    // pointer to plat specific data
    // platform functions can malloc space here if needed;
    // deconfigGard dtor will free()
    void *iv_platDeconfigGard;

    /**
     * @brief  Flag indicating if _deconfigureTarget has deconfigured an
     * x/a bus endpoint.
     *
     * Used by _invokeDeconfigureAssocProc.  If true,
     * _invokeDeconfigureAssocProc will execute and then call
     * _deconfigureAssocProc.  If false, there is no work to be done
     * and _invokeDeconfigureAssocProc will break and return.
     */
    bool iv_XABusEndpointDeconfigured;

}; // DeconfigGard
HWAS_DECLARE_SINGLETON(HWAS::DeconfigGard,theDeconfigGardSingleton);

}

#endif


text:
module Histogram
  module Framework
    module Rails
      class ActionControllerSubscriber < ActiveSupport::LogSubscriber
        def process_action(e)
          Histogram::DB.record(e.transaction_id).controller = e
          Histogram::DB.compress(e.transaction_id)
        end
      end

      class ActionViewSubscriber < ActiveSupport::LogSubscriber
        def render_template(e)
          record = Histogram::DB.record(e.transaction_id)
          record.views << e
          record.layout = e.payload[:layout]
        end

        def render_partial(e); end
        def render_collection(e); end
      end

      class ActiveRecordSubscriber < ActiveSupport::LogSubscriber
        IGNORE_PAYLOAD_NAMES = ["SCHEMA", "EXPLAIN"]

        def sql(e)
          return if IGNORE_PAYLOAD_NAMES.include? e.payload[:name]
          name = e.payload[:name]
          return if name && name.include?("SchemaMigration")
          Histogram::DB.record(e.transaction_id).models << e
        end
      end
    end
  end
end

Histogram::Framework::Rails::ActionControllerSubscriber.attach_to :action_controller
Histogram::Framework::Rails::ActionViewSubscriber.attach_to :action_view
Histogram::Framework::Rails::ActiveRecordSubscriber.attach_to :active_record
#Histogram::Framework::Rails::ActionMailerSubscriber.attach_to :action_mailer


text:
struct NVGLUframebuffer {
	struct NVGcontext* ctx;
	GLuint fbo;
	GLuint rbo;
	GLuint texture;
	int image;
};

// Helper function to create GL frame buffer to render to.
struct NVGLUframebuffer* nvgluCreateFramebuffer(struct NVGcontext* ctx, int w, int h);
void nvgluDeleteFramebuffer(struct NVGcontext* ctx, struct NVGLUframebuffer* fb);

#endif // NANOVG_GL_UTILS_H

#ifdef NANOVG_GL_IMPLEMENTATION

#if defined(NANOVG_GL3)
// FBO is core in OpenGL 3>.
#	define NANOVG_FBO_VALID 1
#elif defined(NANOVG_GL2)
// On OS X including glext defines FBO on GL2 too.
#	ifdef __APPLE__
#		include <OpenGL/glext.h>
#		define NANOVG_FBO_VALID 1
#	endif
#endif

struct NVGLUframebuffer* nvgluCreateFramebuffer(struct NVGcontext* ctx, int w, int h)
{
#ifdef NANOVG_FBO_VALID
	struct NVGLUframebuffer* fb = NULL;
	fb = (struct NVGLUframebuffer*)malloc(sizeof(struct NVGLUframebuffer));
	if (fb == NULL) goto error;
	memset(fb, 0, sizeof(struct NVGLUframebuffer));

	fb->image = nvgCreateImageRGBA(ctx, w, h, NULL);
	fb->texture = nvglImageHandle(ctx, fb->image);
	nvglImageFlags(ctx, fb->image, NVGL_TEXTURE_FLIP_Y | NVGL_TEXTURE_PREMULTIPLIED);

	// frame buffer object
	glGenFramebuffers(1, &fb->fbo);
	glBindFramebuffer(GL_FRAMEBUFFER, fb->fbo);

	// render buffer object
	glGenRenderbuffers(1, &fb->rbo);
	glBindRenderbuffer(GL_RENDERBUFFER, fb->rbo);
	glRenderbufferStorage(GL_RENDERBUFFER, GL_STENCIL_INDEX8, w, h);

	// combine all
	glFramebufferTexture2D(GL_FRAMEBUFFER, GL_COLOR_ATTACHMENT0, GL_TEXTURE_2D, fb->texture, 0);
	glFramebufferRenderbuffer(GL_FRAMEBUFFER, GL_STENCIL_ATTACHMENT, GL_RENDERBUFFER, fb->rbo);

	if (glCheckFramebufferStatus(GL_FRAMEBUFFER) != GL_FRAMEBUFFER_COMPLETE) goto error;

	return fb;
error:
	nvgluDeleteFramebuffer(ctx, fb);
	return NULL;
#else
	NVG_NOTUSED(ctx);
	NVG_NOTUSED(w);
	NVG_NOTUSED(h);
	return NULL;
#endif
}

void nvgluBindFramebuffer(struct NVGLUframebuffer* fb)
{
#ifdef NANOVG_FBO_VALID
	glBindFramebuffer(GL_FRAMEBUFFER, fb != NULL ? fb->fbo : 0);
#else
	NVG_NOTUSED(fb);
#endif
}

void nvgluDeleteFramebuffer(struct NVGcontext* ctx, struct NVGLUframebuffer* fb)
{
#ifdef NANOVG_FBO_VALID
	if (fb == NULL) return;
	if (fb->fbo != 0)
		glDeleteFramebuffers(1, &fb->fbo);
	if (fb->rbo != 0)
		glDeleteRenderbuffers(1, &fb->rbo);
	if (fb->image >= 0)
		nvgDeleteImage(ctx, fb->image);
	fb->fbo = 0;
	fb->rbo = 0;
	fb->texture = 0;
	fb->image = -1;
	free(fb);
#else
	NVG_NOTUSED(ctx);
	NVG_NOTUSED(fb);
#endif
}

#endif // NANOVG_GL_IMPLEMENTATION


text: pg-learning-2015-treehouse-javascript-node-api


text:
--TEST--
Test symlink(), linkinfo(), link() and is_link() functions : usage variations - access/update file through softlink
--SKIPIF--
<?php
if (substr(PHP_OS, 0, 3) == 'WIN') {
    die('skip no symlinks on Windows');
}
?>
--FILE--
<?php
/* Prototype: bool symlink ( string $target, string $link );
   Description: creates a symbolic link to the existing target with the specified name link

   Prototype: bool is_link ( string $filename );
   Description: Tells whether the given file is a symbolic link.

   Prototype: bool link ( string $target, string $link );
   Description: Create a hard link

   Prototype: int linkinfo ( string $path );
   Description: Gets information about a link
*/

/* Variation 3 : Create file and a soft link to the file
                 Access data of the file through the soft link
                 Update the file through soft link
                 Check size of file and soft link link
*/

$file_path = dirname(__FILE__);
echo "*** Accessing and updating data of file through soft link ***\n";
// Creating file and inserting data into it
$filename = "$file_path/symlink_link_linkinfo_is_link_variation3.tmp";

// create temp file
$file = fopen($filename, "w");

// create soft link to file
$linkname = "$file_path/symlink_link_linkinfo_is_link_link_variation3.tmp";
var_dump( symlink($filename, $linkname) );
// storing size of symlink in a local variable
$link_stat = lstat($linkname);  // lstat of link
$link_size = $link_stat[7];  // size of soft link

// fill data into file
fwrite($file, str_repeat("text", 20) );
fclose($file);

echo "\n-- Access data of the file through the soft link --\n";
$data_from_link = file_get_contents($linkname);  // data read from $filename
var_dump( $data_from_link );

echo "\n-- Check size of soft link and file --\n";
var_dump( filesize($filename) );
var_dump( filesize($linkname) );

// taking lstat of symlink
$stat = lstat($linkname);
// checking that size of symlink remains same
if ($link_size == $stat[7])
  echo "\nSoft link size remains same \n";
else
  echo "\nWarning: Soft link size has changed \n";

echo "\n-- Updating file with data through soft link --\n";
// append link with data
$fp = fopen($linkname, "a");  // open in append mode
fwrite($fp, "Hello World");
fclose($fp);

// now check temp file for data; it should append "Hello World"
$data_from_file = file_get_contents($filename);
var_dump( $data_from_file );

echo "\n-- Check size of soft link and file --\n";
var_dump( filesize($filename) );
var_dump( filesize($linkname) );

// taking lstat of symlink
$stat = lstat($linkname);
// checking that size of symlink remains same
if ($link_size == $stat[7])
  echo "\nSoft link size remains same \n";
else
  echo "\nWarning: Soft link size has changed \n";

echo "\n-- Updating file with data and check data through soft link --\n";
// write to temp file
$file = fopen($filename, "w");
fwrite($file, "Hello World");
fclose($file);

// now check link for data; it should echo "Hello World"
$data_from_link = file_get_contents($linkname);
var_dump( $data_from_link );

echo "\n-- Check size of soft link and file --\n";
var_dump( filesize($filename) );
var_dump( filesize($linkname) );

// taking lstat of symlink
$stat = lstat($linkname);
// checking that size of symlink remains same
if ($link_size == $stat[7])
  echo "\nSoft link size remains same \n";
else
  echo "\nWarning: Soft link size has changed \n";

// delete the link
unlink($linkname);
// delete the temporary file
unlink($filename);

echo "Done\n";
?>
--EXPECTF--
*** Accessing and updating data of file through soft link ***
bool(true)

-- Access data of the file through the soft link --
string(80) "texttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttext"

-- Check size of soft link and file --
int(80)
int(80)

Soft link size remains same

-- Updating file with data through soft link --
string(91) "texttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttexttextHello World"

-- Check size of soft link and file --
int(91)
int(91)

Soft link size remains same

-- Updating file with data and check data through soft link --
string(11) "Hello World"

-- Check size of soft link and file --
int(11)
int(11)

Soft link size remains same
Done


text:
<!DOCTYPE html>

<link href="resources/grid.css" rel="stylesheet">


text:
package org.vitrivr.cineast.core.data.providers;

import org.vitrivr.cineast.core.data.raw.images.MultiImage;

public interface AvgImgProvider {

  /**
   * @return the aggregated pixel-wise average of multiple images. By default, the {@link MultiImage}.EMPTY_MULTIIMAGE is returned.
   */
  public default MultiImage getAvgImg() {
    return MultiImage.EMPTY_MULTIIMAGE;
  }

}


text:
package org.springframework.cloud.dataflow.core;

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

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * @author David Turanski
 **/
public abstract class AbstractTaskPlatformFactory<P extends AbstractPlatformProperties<?>> implements TaskPlatformFactory {

	protected Logger logger = LoggerFactory.getLogger(this.getClass());

	protected final P platformProperties;

	protected final String platformType;

	protected AbstractTaskPlatformFactory(P platformProperties, String platformType){
		this.platformProperties = platformProperties;
		this.platformType = platformType;
	}

	@Override
	public TaskPlatform createTaskPlatform() {
		return new TaskPlatform(platformType, createLaunchers());
	}

	protected List<Launcher> createLaunchers() {
		List<Launcher> launchers = new ArrayList<>();

		for (String account : platformProperties.getAccounts().keySet()) {
			try {
				launchers.add(createLauncher(account));
			}
			catch (Exception e) {
				logger.error("{} platform account [{}] could not be registered: {}",
					platformType, account, e);
				throw new IllegalStateException(e.getMessage(), e);
			}
		}

		return launchers;
	}
}


text:
using System;
using System.Globalization;
using System.Threading;
using System.Threading.Tasks;
using Azure;
using Azure.Core;
using Azure.Core.Pipeline;
using Azure.ResourceManager;

namespace Azure.ResourceManager.Sql
{
    /// <summary>
    /// A Class representing a RecommendedAction along with the instance operations that can be performed on it.
    /// If you have a <see cref="ResourceIdentifier" /> you can construct a <see cref="RecommendedActionResource" />
    /// from an instance of <see cref="ArmClient" /> using the GetRecommendedActionResource method.
    /// Otherwise you can get one from its parent resource <see cref="SqlDatabaseAdvisorResource" /> using the GetRecommendedAction method.
    /// </summary>
    public partial class RecommendedActionResource : ArmResource
    {
        /// <summary> Generate the resource identifier of a <see cref="RecommendedActionResource"/> instance. </summary>
        public static ResourceIdentifier CreateResourceIdentifier(string subscriptionId, string resourceGroupName, string serverName, string databaseName, string advisorName, string recommendedActionName)
        {
            var resourceId = $"/subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}";
            return new ResourceIdentifier(resourceId);
        }

        private readonly ClientDiagnostics _recommendedActionDatabaseRecommendedActionsClientDiagnostics;
        private readonly DatabaseRecommendedActionsRestOperations _recommendedActionDatabaseRecommendedActionsRestClient;
        private readonly RecommendedActionData _data;

        /// <summary> Initializes a new instance of the <see cref="RecommendedActionResource"/> class for mocking. </summary>
        protected RecommendedActionResource()
        {
        }

        /// <summary> Initializes a new instance of the <see cref = "RecommendedActionResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="data"> The resource that is the target of operations. </param>
        internal RecommendedActionResource(ArmClient client, RecommendedActionData data) : this(client, data.Id)
        {
            HasData = true;
            _data = data;
        }

        /// <summary> Initializes a new instance of the <see cref="RecommendedActionResource"/> class. </summary>
        /// <param name="client"> The client parameters to use in these operations. </param>
        /// <param name="id"> The identifier of the resource that is the target of operations. </param>
        internal RecommendedActionResource(ArmClient client, ResourceIdentifier id) : base(client, id)
        {
            _recommendedActionDatabaseRecommendedActionsClientDiagnostics = new ClientDiagnostics("Azure.ResourceManager.Sql", ResourceType.Namespace, Diagnostics);
            TryGetApiVersion(ResourceType, out string recommendedActionDatabaseRecommendedActionsApiVersion);
            _recommendedActionDatabaseRecommendedActionsRestClient = new DatabaseRecommendedActionsRestOperations(Pipeline, Diagnostics.ApplicationId, Endpoint, recommendedActionDatabaseRecommendedActionsApiVersion);
#if DEBUG
			ValidateResourceId(Id);
#endif
        }

        /// <summary> Gets the resource type for the operations. </summary>
        public static readonly ResourceType ResourceType = "Microsoft.Sql/servers/databases/advisors/recommendedActions";

        /// <summary> Gets whether or not the current instance has data. </summary>
        public virtual bool HasData { get; }

        /// <summary> Gets the data representing this Feature. </summary>
        /// <exception cref="InvalidOperationException"> Throws if there is no data loaded in the current instance. </exception>
        public virtual RecommendedActionData Data
        {
            get
            {
                if (!HasData)
                    throw new InvalidOperationException("The current instance does not have data, you must call Get first.");
                return _data;
            }
        }

        internal static void ValidateResourceId(ResourceIdentifier id)
        {
            if (id.ResourceType != ResourceType)
                throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "Invalid resource type {0} expected {1}", id.ResourceType, ResourceType), nameof(id));
        }

        /// <summary>
        /// Gets a database recommended action.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}
        /// Operation Id: DatabaseRecommendedActions_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual async Task<Response<RecommendedActionResource>> GetAsync(CancellationToken cancellationToken = default)
        {
            using var scope = _recommendedActionDatabaseRecommendedActionsClientDiagnostics.CreateScope("RecommendedActionResource.Get");
            scope.Start();
            try
            {
                var response = await _recommendedActionDatabaseRecommendedActionsRestClient.GetAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken).ConfigureAwait(false);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new RecommendedActionResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Gets a database recommended action.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}
        /// Operation Id: DatabaseRecommendedActions_Get
        /// </summary>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        public virtual Response<RecommendedActionResource> Get(CancellationToken cancellationToken = default)
        {
            using var scope = _recommendedActionDatabaseRecommendedActionsClientDiagnostics.CreateScope("RecommendedActionResource.Get");
            scope.Start();
            try
            {
                var response = _recommendedActionDatabaseRecommendedActionsRestClient.Get(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, cancellationToken);
                if (response.Value == null)
                    throw new RequestFailedException(response.GetRawResponse());
                return Response.FromValue(new RecommendedActionResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Updates a database recommended action.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}
        /// Operation Id: DatabaseRecommendedActions_Update
        /// </summary>
        /// <param name="data"> The requested recommended action resource state. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual async Task<Response<RecommendedActionResource>> UpdateAsync(RecommendedActionData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _recommendedActionDatabaseRecommendedActionsClientDiagnostics.CreateScope("RecommendedActionResource.Update");
            scope.Start();
            try
            {
                var response = await _recommendedActionDatabaseRecommendedActionsRestClient.UpdateAsync(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, data, cancellationToken).ConfigureAwait(false);
                return Response.FromValue(new RecommendedActionResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }

        /// <summary>
        /// Updates a database recommended action.
        /// Request Path: /subscriptions/{subscriptionId}/resourceGroups/{resourceGroupName}/providers/Microsoft.Sql/servers/{serverName}/databases/{databaseName}/advisors/{advisorName}/recommendedActions/{recommendedActionName}
        /// Operation Id: DatabaseRecommendedActions_Update
        /// </summary>
        /// <param name="data"> The requested recommended action resource state. </param>
        /// <param name="cancellationToken"> The cancellation token to use. </param>
        /// <exception cref="ArgumentNullException"> <paramref name="data"/> is null. </exception>
        public virtual Response<RecommendedActionResource> Update(RecommendedActionData data, CancellationToken cancellationToken = default)
        {
            Argument.AssertNotNull(data, nameof(data));

            using var scope = _recommendedActionDatabaseRecommendedActionsClientDiagnostics.CreateScope("RecommendedActionResource.Update");
            scope.Start();
            try
            {
                var response = _recommendedActionDatabaseRecommendedActionsRestClient.Update(Id.SubscriptionId, Id.ResourceGroupName, Id.Parent.Parent.Parent.Name, Id.Parent.Parent.Name, Id.Parent.Name, Id.Name, data, cancellationToken);
                return Response.FromValue(new RecommendedActionResource(Client, response.Value), response.GetRawResponse());
            }
            catch (Exception e)
            {
                scope.Failed(e);
                throw;
            }
        }
    }
}


text:
%% The main function for IPCV project 3

%% Initialize the project directory

[PROJ_DIR, mname, mext] = fileparts(mfilename('fullpath'));
PROJ_DIR = [PROJ_DIR, '/'];
cd(PROJ_DIR);

addpath(genpath(PROJ_DIR));

%% Start by camera calibration

    % Define subject and calibration paths
    SUBJ = 'subject1';      % Possibilities 1,2,4
    CALIB= 'Calibratie 2/'; % Possibilities 1,2
    IMG  = '_2';            % Possibilties 1,2,365,729,1093,1457

    % Load stereo calibration
load([PROJ_DIR, CALIB, 'sP_MR.mat'])
load([PROJ_DIR, CALIB, 'sP_ML.mat'])
load([PROJ_DIR, CALIB, 'sP_LR.mat'])

    % Load face images
im_L = imread([PROJ_DIR, SUBJ, '/', SUBJ, 'Left/',   SUBJ, '_Left',  IMG,'.jpg']);
im_M = imread([PROJ_DIR, SUBJ, '/', SUBJ, 'Middle/', SUBJ, '_Middle',IMG,'.jpg']);
im_R = imread([PROJ_DIR, SUBJ, '/', SUBJ, 'Right/',  SUBJ, '_Right', IMG,'.jpg']);

    % Show the original images
figure(1); clf
    subplot(1,3,1);
        imshow(im_L)
    subplot(1,3,2);
        imshow(im_M)
        title('Original images')
    subplot(1,3,3);
        imshow(im_R)

%% Remove background in im_*_noBG and store the mask to mask_*
%   (in mask_* BG pixels are 0 and face 1)

    % Select good settings for the subject
switch SUBJ(end);
    case '1'
        edgeThresh  = 0.1;
        strelVal    = 2;
    case '2'
        edgeThresh  = 0.05;
        strelVal    = 4;
    case '4'
        edgeThresh  = 0.03;
        strelVal    = 5;
end

    % Remove the backgrounds from each image
plotFlag = false;
[im_L_noBG, mask_L] = removeBackground(im_L, edgeThresh, strelVal, plotFlag);
[im_M_noBG, mask_M] = removeBackground(im_M, edgeThresh, strelVal, plotFlag);
[im_R_noBG, mask_R] = removeBackground(im_R, edgeThresh, strelVal, plotFlag);

    % Show the result
figure;
    imshow(im_L_noBG);
figure;
    imshow(im_M_noBG);
figure;
    imshow(im_R_noBG);

%% Normalize image intesities to correspond middle image

im_L_norm = normalizeImages(im_L, im_M);
im_R_norm = normalizeImages(im_R, im_M);

%% Rectify

    % How'd you like the recitification viewed?
OutpView = 'full';

    % Rectify the images
[im_Mr_rec, im_R_rec] = rectifyStereoImages(im_M, im_R_norm, sP_MR,...
                            'OutputView',OutpView);
[im_Ml_rec, im_L_rec] = rectifyStereoImages(im_M, im_L_norm, sP_ML,...
                            'OutputView',OutpView);

	% Do the same for masks
[mask_Mr_rec, mask_R_rec] = rectifyStereoImages(mask_M, mask_R, sP_MR,...
                            'OutputView',OutpView);
[mask_Ml_rec, mask_L_rec] = rectifyStereoImages(mask_M, mask_L, sP_ML,...
                            'OutputView',OutpView);

	% Apply the masks to see everything's fine
masked_Mr_rec = im_Mr_rec .* uint8(repmat(mask_Mr_rec,[1,1,3]));
masked_R_rec  = im_R_rec  .* uint8(repmat(mask_R_rec,[1,1,3]));

masked_Ml_rec = im_Ml_rec .* uint8(repmat(mask_Ml_rec,[1,1,3]));
masked_L_rec  = im_L_rec  .* uint8(repmat(mask_L_rec,[1,1,3]));

    % And visualise
figure;
    CreateAxes(3,1,1);
        imshow(stereoAnaglyph(masked_Mr_rec, masked_R_rec));
	CreateAxes(3,1,2);
        imshow(stereoAnaglyph(masked_Ml_rec, masked_L_rec));

%% Disparity

    % Choose from predetermined disparity range
    %   These don't really matter, but I'm afraid to touch
 switch SUBJ(end);
    case '1'
        dispar_values_R = [ 230,  350];
        dispar_values_L = [-550, -200];
    case '2'
        dispar_values_R = [ 230,  380];
        dispar_values_L = [-580, -300];
    case '4'
        dispar_values_R = [ 150,  600];
        dispar_values_L = [-560, -150];
 end

    % Calculate the disparities
	%   There's some stupid flipping and multiplying, because the disparity
	%   seems to operate on black magick.
disparmap_R = mapDisparity(im_R_rec, im_Mr_rec, flip(dispar_values_R).*-1) .* -1;
disparmap_L = mapDisparity(im_Ml_rec, im_L_rec, dispar_values_L).*-1;

    % And visualise
figure;
    imshow(disparmap_R)
figure;
    imshow(disparmap_L)

%% Erode the masks to cut a bit of the image border

er_fact = 30;

mask_Mr_eroded = imerode(mask_Mr_rec, strel('diamond', er_fact));
mask_R_eroded = imerode(mask_R_rec  , strel('diamond', er_fact));
mask_Ml_eroded = imerode(mask_Ml_rec, strel('diamond', er_fact));

%% Fill Gaps with relaxation
%   This part is for writing the report images later on
gv = -1;

disparmap = disparmap_R.*mask_Mr_rec;
disparmap(isnan(disparmap)) = 0;
disparmap(mask_Mr_rec==1 & disparmap==0) = gv;
disparmap_f = relaxgaps(disparmap,gv,1,300,0.001,0);
disparmap_R(isnan(disparmap_R)) = 0;
disparmap_L(isnan(disparmap_L)) = 0;

disparmap_R(mask_R_rec==1  & disparmap_R==0) = -1;
disparmap_L(mask_Ml_rec==1 & disparmap_L==0) = -1;

disparmap_fR = relaxgaps(disparmap_R ,gv,1,300,0.001,0);
disparmap_fL = relaxgaps(disparmap_L ,gv,1,300,0.001,0);

figure; imshow(disparmap_fR,[])
figure; imshow(disparmap_fL,[])

%% Laplacian filter plus new relaxation

    % This part again for later images
threshold = 1;
[disparmap_fl,lapfilt] = laplacianFilter(disparmap_f,threshold,gv);
figure; imshow(disparmap_fl,[]); title('Laplacian filtered')
[disparmap_flf,its] = relaxgaps(disparmap_fl,gv,1,400,0.001,0);

figure; imshow(disparmap_flf,[]); title('Relaxed Laplacian filtered')

    % And these for pointCloud computations
disparmap_fR_lap = laplacianFilter(disparmap_fR, threshold, gv);
figure; imshow(disparmap_fR_lap,[]); title('Laplacian filtered')
disparmap_fR_2 = relaxgaps(disparmap_fR_lap,gv,1,300,0.001,0);
figure; imshow(disparmap_fR_2,[]); title('Relaxed Laplacian filtered')

    % Above for Right, below for Left
disparmap_fL_lap = laplacianFilter(disparmap_fL, threshold, gv);
figure; imshow(disparmap_fL_lap,[]); title('Laplacian filtered')
disparmap_fL_2 = relaxgaps(disparmap_fL_lap, gv,1,300,0.001,0);
figure; imshow(disparmap_fL_2,[]); title('Relaxed Laplacian filtered')

%% Plot Face Mesh
ptCloud_R = facemesh(disparmap_fR_2.*mask_R_eroded, im_R_rec );
ptCloud_L = facemesh(disparmap_fL_2.*mask_Ml_eroded, im_Ml_rec);

%% Write Report Images
writeReportImages = true;

if writeReportImages
    % Crop parameters
    x = 800;
    y = 100;
    w = 600;
    h = 700;

    % Crop images and adjust range for export
    disparitygaps_c = mat2gray(imcrop(disparmap,    [x y w h]));
    disparityfill_c = mat2gray(imcrop(disparmap_f,  [x y w h]));
    disparitylapf_c = mat2gray(imcrop(lapfilt,      [x y w h]));
    disparityflf_c  = mat2gray(imcrop(disparmap_flf,[x y w h]));

    % Write images
    imwrite(disparitygaps_c,'./out/disparity-gaps.png')
    imwrite(disparityfill_c,'./out/disparity-fill.png')
    imwrite(disparitylapf_c,'./out/disparity-lapf.png')
    imwrite(disparityflf_c, './out/disparity-flf.png')
end

%% Point cloud figure creation
ptCloud_R_ds = pcdownsample(ptCloud_R, 'random',.2);
ptCloud_L_ds = pcdownsample(ptCloud_L, 'random',.2);

    % Read the location
pts_R.Location = ptCloud_R_ds.Location;
pts_L.Location = ptCloud_L_ds.Location;

    % And colour info
pts_R.Color    = ptCloud_R_ds.Color;
pts_L.Color    = ptCloud_L_ds.Color;

    % Weed out parts very close and far
include_R      = pts_R.Location(:,3) > 1000 & pts_R.Location(:,3) < 1400;
include_L      = pts_L.Location(:,3) > 1000 & pts_L.Location(:,3) < 1400;

    % Reconstruct the pointCloude
ptCloud_R_include = pointCloud(pts_R.Location(include_R,:),...
                        'Color',pts_R.Color(include_R,:));
ptCloud_L_include = pointCloud(pts_L.Location(include_L,:),...
                        'Color',pts_L.Color(include_L,:));

	% Try to align the two meshes
    %   Spoiler alert: doesn't work
[tform,movingReg] = pcregrigid(ptCloud_L_include, ptCloud_R_include, 'Extrapolate', true);

%% And visualize the outcome, once more
figure;
    CreateAxes(2,2,1); axis off
pcshow(ptCloud_R_include);
    CreateAxes(2,2,2); axis off
pcshow(ptCloud_L_include);
    CreateAxes(2,2,3); axis off
pcshow(ptCloud_L); hold on;
pcshow(ptCloud_R)
    CreateAxes(2,2,4); axis off
pcshow(ptCloud_R_include); hold on;
pcshow(  movingReg );


text:
"""
Standardize names of data files from the Pennsylvania Secretary of State.

The state offers CSV files containing precinct-level results for regularly scheduled primary and general elections; these were split from a single
zip file into election-specific files and thus have no `raw_url` attribute. Special elections are pre-processed CSV files from HTML files. All files
are available in the https://github.com/openelections/openelections-data-pa repository.
"""
from future import standard_library
standard_library.install_aliases()
from os.path import join
import json
import unicodecsv
import urllib.parse
import requests

from openelex import PROJECT_ROOT
from openelex.base.datasource import BaseDatasource
from openelex.lib import build_github_url

class Datasource(BaseDatasource):

    # PUBLIC INTERFACE
    def mappings(self, year=None):
        """Return array of dicts containing source url and
        standardized filename for raw results file, along
        with other pieces of metadata
        """
        mappings = []
        for yr, elecs in list(self.elections(year).items()):
            mappings.extend(self._build_metadata(yr, elecs))
        return mappings

    def target_urls(self, year=None):
        "Get list of source data urls, optionally filtered by year"
        return [item['raw_url'] for item in self.mappings(year)]

    def filename_url_pairs(self, year=None):
        return [(item['generated_filename'], self._url_for_fetch(item))
                for item in self.mappings(year)]

    # PRIVATE METHODS

    def _build_metadata(self, year, elections):
        meta = []
        year_int = int(year)
        for election in elections:
            if election['special']:
                results = [x for x in self._url_paths() if x['date'] == election['start_date'] and x['special'] == True]
            else:
                results = [x for x in self._url_paths() if x['date'] == election['start_date'] and x['special'] == False]
            for result in results:
                if election['direct_links']:
                    raw_url = election['direct_links'][0]
                else:
                    raw_url = None
                generated_filename = self._generate_filename(election['start_date'], election['race_type'], result)
                meta.append({
                    "generated_filename": generated_filename,
                    "raw_url": raw_url,
                    "pre_processed_url": build_github_url(self.state, generated_filename),
                    "ocd_id": 'ocd-division/country:us/state:pa',
                    "name": 'Pennsylvania',
                    "election": election['slug']
                })
        return meta

    def _generate_filename(self, start_date, election_type, result):
        if result['district'] == '':
            office = result['office']
        else:
            office = result['office'] + '__' + result['district']
        if result['special']:
            election_type = 'special__' + election_type
        else:
            election_type = election_type+'__precinct'
        bits = [
            start_date.replace('-',''),
            self.state.lower(),
            election_type,
            office
        ]
        if office == '':
            bits.remove(office)
        name = "__".join(bits) + '.csv'
        return name

    def _jurisdictions(self):
        """Pennsylvania counties"""
        return self.jurisdiction_mappings()

    def _url_for_fetch(self, mapping):
        if mapping['pre_processed_url']:
            return mapping['pre_processed_url']
        else:
            return mapping['raw_url']


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

import static org.rauschig.wicketjs.jquery.JQuery.$;

import java.util.List;

import org.apache.wicket.Component;
import org.apache.wicket.ajax.AjaxRequestTarget;
import org.apache.wicket.ajax.attributes.AjaxRequestAttributes;
import org.apache.wicket.ajax.form.AjaxFormChoiceComponentUpdatingBehavior;
import org.apache.wicket.behavior.Behavior;
import org.apache.wicket.markup.ComponentTag;
import org.apache.wicket.markup.html.form.IChoiceRenderer;
import org.apache.wicket.model.IModel;
import org.cdlflex.ui.markup.html.form.ButtonRadioChoice;
import org.rauschig.wicketjs.IJavaScript;
import org.rauschig.wicketjs.JsIdentifier;
import org.rauschig.wicketjs.JsStatements;
import org.rauschig.wicketjs.ajax.AjaxCallListener;
import org.rauschig.wicketjs.ajax.JsAjaxCallListener;

/**
 * ButtonRadioChoice with ajax onChange behavior listeners.
 *
 * Notice: This isn't very well implemented, because it works around a discrepancy between bootstrap's 'data-toggle' for
 * radio buttons (inherited from ButtonRadioChoice) and Wickets AjaxFormChoiceComponentUpdatingBehavior. Bootstrap
 * somehow causes the event bubbling to stop, which means that the wicket ajax event is never called. The front-end
 * functionality (setting label classes) is thus solved via wicket-js and jquery.
 *
 * @param <T> Model object type
 */
public abstract class AjaxButtonRadioChoice<T> extends ButtonRadioChoice<T> {

    private static final long serialVersionUID = 1L;

    public AjaxButtonRadioChoice(String id) {
        super(id);
    }

    public AjaxButtonRadioChoice(String id, List<? extends T> choices) {
        super(id, choices);
    }

    public AjaxButtonRadioChoice(String id, List<? extends T> choices, IChoiceRenderer<? super T> renderer) {
        super(id, choices, renderer);
    }

    public AjaxButtonRadioChoice(String id, IModel<T> model, List<? extends T> choices) {
        super(id, model, choices);
    }

    public AjaxButtonRadioChoice(String id, IModel<T> model, List<? extends T> choices,
            IChoiceRenderer<? super T> renderer) {
        super(id, model, choices, renderer);
    }

    public AjaxButtonRadioChoice(String id, IModel<? extends List<? extends T>> choices) {
        super(id, choices);
    }

    public AjaxButtonRadioChoice(String id, IModel<T> model, IModel<? extends List<? extends T>> choices) {
        super(id, model, choices);
    }

    public AjaxButtonRadioChoice(String id, IModel<? extends List<? extends T>> choices,
            IChoiceRenderer<? super T> renderer) {
        super(id, choices, renderer);
    }

    public AjaxButtonRadioChoice(String id, IModel<T> model, IModel<? extends List<? extends T>> choices,
            IChoiceRenderer<? super T> renderer) {
        super(id, model, choices, renderer);
    }

    @Override
    protected void onComponentTag(ComponentTag tag) {
        super.onComponentTag(tag);

        tag.remove("data-toggle");
    }

    @Override
    protected void onInitialize() {
        super.onInitialize();

        add(newUpdatingBehavior());
    }

    /**
     * Creates the Behavior that should call {@link #onSelectionChange}.
     *
     * @return a new behavior instance
     */
    protected Behavior newUpdatingBehavior() {
        return new AjaxFormChoiceComponentUpdatingBehavior() {
            private static final long serialVersionUID = 1L;

            @Override
            protected void onUpdate(AjaxRequestTarget target) {
                AjaxButtonRadioChoice.this.onSelectionChange(getModelObject(), target);
            }

            @Override
            protected void updateAjaxAttributes(AjaxRequestAttributes attributes) {
                super.updateAjaxAttributes(attributes);

                attributes.getAjaxCallListeners().add(new AjaxCallListener(new JsAjaxCallListener() {
                    private static final long serialVersionUID = 1L;

                    @Override
                    public IJavaScript getBeforeHandler(Component component) {
                        JsIdentifier currentTarget = new JsIdentifier("attrs.event.currentTarget");
                        JsIdentifier target = new JsIdentifier("attrs.event.target");

                        return new JsStatements($("label", currentTarget).removeClass("active"), $(target).parent()
                                .addClass("active"));
                    }
                }));
            }
        };
    }

    /**
     * Called when the selection changes.
     *
     * @param selection the new selection
     *
     * @param target the ajax request target
     */
    protected abstract void onSelectionChange(T selection, AjaxRequestTarget target);
}


text:
<?php

namespace Template\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

use Template\Entity\Template;

class IndexController extends AbstractActionController
{
    protected $EntityManager;

    const TEMPLATE_REPO = "Template\Entity\Template";

    public function indexAction() {
        $request = $this->getRequest();

        $form_id = 5; //Hard coded value

        $forms = $this->getEntityManager()->getRepository('Forms\Entity\Form')->findAll();

        if(!isset($forms[0]) || empty($forms[0])) {
            throw new \Doctrine\ORM\EntityNotFoundException("Form" . ' with ID: [ ' . $template_id . ' ] was not found.');
        }

        $form = $forms[0];

        if($request->isPost()) {
            $data = $request->getPost();
            $template = new Template();

            $template->setTemplateName($data['template_name']);
            $template->setContent($data['template-editor']);

            $this->getEntityManager()->persist($template);
            $this->getEntityManager()->flush();

            return $this->redirect()->toRoute('template', ['action' => 'edit', 'id' => $template->getTemplateId()]);
        }

        return new ViewModel(['template' => new Template(), 'action' => 'NEW', 'form' => $form]);
    }

    public function editAction() {
        $request = $this->getRequest();
        $template_id = $this->params()->fromRoute('id');

        $forms = $this->getEntityManager()->getRepository('Forms\Entity\Form')->findAll();

        if(!isset($forms[0]) || empty($forms[0])) {
            throw new \Doctrine\ORM\EntityNotFoundException("Form" . ' with ID: [ ' . $template_id . ' ] was not found.');
        }

        $form = $forms[0];

        $template = $this->getEntityManager()->getRepository(self::TEMPLATE_REPO)->findBy(['template_id'=>$template_id]);

        if(!isset($template[0]) || empty($template[0])) {
            throw new \Doctrine\ORM\EntityNotFoundException(self::TEMPLATE_REPO . ' with ID: [ ' . $template_id . ' ] was not found.');
        }

        $template = $template[0];

        if($request->isPost()) {
            $data = $request->getPost();
            $template->setTemplateName($data['template_name']);
            $template->setContent($data['template-editor']);
            $this->getEntityManager()->persist($template);
            $this->getEntityManager()->flush();

            return $this->redirect()->toRoute('template', ['action' => 'edit', 'id' => $template->getTemplateId()]);
        }

        $view = new ViewModel(['template' => $template, 'action' => 'EDIT', 'form' => $form]);
        $view->setTemplate('template/index/index');
        return $view;
    }
    public function resetAction() {
        $em = $this->getEntityManager();
        $meta = array(
            $em->getClassMetadata('Template\Entity\Template'),
            $em->getClassMetadata('Forms\Entity\Form'),
            $em->getClassMetadata('Forms\Entity\Field'),
            $em->getClassMetadata('Folders\Entity\Folder'),
            $em->getClassMetadata('Folders\Entity\FieldValue')
	);
        $tool = new \Doctrine\ORM\Tools\SchemaTool($em);
        $tool->updateSchema($meta);
        exit('update schema done');
    }

    public function setEntityManager($entityManager) {
        $this->EntityManager = $entityManager;
    }

    public function getEntityManager() {
        return $this->EntityManager;
    }
}


text:
WebInspector.Script = function(sourceID, sourceURL, source, startingLine, errorLine, errorMessage, worldType)
{
    this.sourceID = sourceID;
    this.sourceURL = sourceURL;
    this.source = source;
    this.startingLine = startingLine;
    this.errorLine = errorLine;
    this.errorMessage = errorMessage;
    this.worldType = worldType;

    // if no URL, look for "//@ sourceURL=" decorator
    // note that this sourceURL comment decorator is behavior that FireBug added
    // in it's 1.1 release as noted in the release notes:
    // http://fbug.googlecode.com/svn/branches/firebug1.1/docs/ReleaseNotes_1.1.txt
    if (!sourceURL) {
        // use of [ \t] rather than \s is to prevent \n from matching
        var pattern = /^\s*\/\/[ \t]*@[ \t]*sourceURL[ \t]*=[ \t]*(\S+).*$/m;
        var match = pattern.exec(source);

        if (match)
            this.sourceURL = match[1];
    }
}

WebInspector.Script.WorldType = {
    MAIN_WORLD: 0,
    EXTENSIONS_WORLD: 1
}

WebInspector.Script.WorldType = {
    MAIN_WORLD: 0,
    EXTENSIONS_WORLD: 1
}

WebInspector.Script.prototype = {
    get linesCount()
    {
        if (!this.source)
            return 0;
        this._linesCount = 0;
        var lastIndex = this.source.indexOf("\n");
        while (lastIndex !== -1) {
            lastIndex = this.source.indexOf("\n", lastIndex + 1)
            this._linesCount++;
        }
    }
}


text:
package com.cgomez.model.bibliography;

import java.util.List;

import org.mongojack.MongoCollection;

import com.cgomez.model.AbstractModel;
import com.cgomez.util.constant.BibliographicCitationEnum;

/**
 * The Class BibliographicCitationDBLP.
 *
 * @author Carlos Gomez
 * @since dl-java-1.0
 */
@MongoCollection(name = "bibliographicCitationsDBLP")
public class BibliographicCitationDBLP extends AbstractModel {

    /** The authors. */
    private List<String> authors;

    /** The title. */
    private String title;

    /** The year. */
    private Integer year;

    /** The journal. */
    private String journal;

    /** The booktitle. */
    private String booktitle;

    /** The type. */
    private BibliographicCitationEnum type;

    // dblp attributes
    /** The key. */
    private String key;

    /** The mdate. */
    private String mdate;

    /** The publtype. */
    private String publtype;

    /** The reviewid. */
    private String reviewid;

    /** The rating. */
    private String rating;

    /** The editor. */
    private String editor;

    /** The pages. */
    private String pages;

    /** The address. */
    private String address;

    /** The volume. */
    private String volume;

    /** The number. */
    private String number;

    /** The month. */
    private String month;

    /** The url. */
    private String url;

    /** The ee. */
    private String ee;

    /** The cdrom. */
    private String cdrom;

    /** The citations. */
    private List<String> citations;

    /** The publisher. */
    private String publisher;

    /** The note. */
    private String note;

    /** The crossref. */
    private String crossref;

    /** The isbn. */
    private String isbn;

    /** The series. */
    private String series;

    /** The school. */
    private String school;

    /** The chapter. */
    private String chapter;

    /**
     * Gets the authors.
     *
     * @return the authors
     */
    public List<String> getAuthors() {
        return authors;
    }

    /**
     * Sets the authors.
     *
     * @param authors the new authors
     */
    public void setAuthors(List<String> authors) {
        this.authors = authors;
    }

    /**
     * Gets the title.
     *
     * @return the title
     */
    public String getTitle() {
        return title;
    }

    /**
     * Sets the title.
     *
     * @param title the new title
     */
    public void setTitle(String title) {
        this.title = title;
    }

    /**
     * Gets the year.
     *
     * @return the year
     */
    public Integer getYear() {
        return year;
    }

    /**
     * Sets the year.
     *
     * @param year the new year
     */
    public void setYear(Integer year) {
        this.year = year;
    }

    /**
     * Gets the journal.
     *
     * @return the journal
     */
    public String getJournal() {
        return journal;
    }

    /**
     * Sets the journal.
     *
     * @param journal the new journal
     */
    public void setJournal(String journal) {
        this.journal = journal;
    }

    /**
     * Gets the booktitle.
     *
     * @return the booktitle
     */
    public String getBooktitle() {
        return booktitle;
    }

    /**
     * Sets the booktitle.
     *
     * @param booktitle the new booktitle
     */
    public void setBooktitle(String booktitle) {
        this.booktitle = booktitle;
    }

    /**
     * Gets the type.
     *
     * @return the type
     */
    public BibliographicCitationEnum getType() {
        return type;
    }

    /**
     * Sets the type.
     *
     * @param type the new type
     */
    public void setType(BibliographicCitationEnum type) {
        this.type = type;
    }

    /**
     * Gets the key.
     *
     * @return the key
     */
    public String getKey() {
        return key;
    }

    /**
     * Sets the key.
     *
     * @param key the new key
     */
    public void setKey(String key) {
        this.key = key;
    }

    /**
     * Gets the mdate.
     *
     * @return the mdate
     */
    public String getMdate() {
        return mdate;
    }

    /**
     * Sets the mdate.
     *
     * @param mdate the new mdate
     */
    public void setMdate(String mdate) {
        this.mdate = mdate;
    }

    /**
     * Gets the publtype.
     *
     * @return the publtype
     */
    public String getPubltype() {
        return publtype;
    }

    /**
     * Sets the publtype.
     *
     * @param publtype the new publtype
     */
    public void setPubltype(String publtype) {
        this.publtype = publtype;
    }

    /**
     * Gets the reviewid.
     *
     * @return the reviewid
     */
    public String getReviewid() {
        return reviewid;
    }

    /**
     * Sets the reviewid.
     *
     * @param reviewid the new reviewid
     */
    public void setReviewid(String reviewid) {
        this.reviewid = reviewid;
    }

    /**
     * Gets the rating.
     *
     * @return the rating
     */
    public String getRating() {
        return rating;
    }

    /**
     * Sets the rating.
     *
     * @param rating the new rating
     */
    public void setRating(String rating) {
        this.rating = rating;
    }

    /**
     * Gets the editor.
     *
     * @return the editor
     */
    public String getEditor() {
        return editor;
    }

    /**
     * Sets the editor.
     *
     * @param editor the new editor
     */
    public void setEditor(String editor) {
        this.editor = editor;
    }

    /**
     * Gets the pages.
     *
     * @return the pages
     */
    public String getPages() {
        return pages;
    }

    /**
     * Sets the pages.
     *
     * @param pages the new pages
     */
    public void setPages(String pages) {
        this.pages = pages;
    }

    /**
     * Gets the address.
     *
     * @return the address
     */
    public String getAddress() {
        return address;
    }

    /**
     * Sets the address.
     *
     * @param address the new address
     */
    public void setAddress(String address) {
        this.address = address;
    }

    /**
     * Gets the volume.
     *
     * @return the volume
     */
    public String getVolume() {
        return volume;
    }

    /**
     * Sets the volume.
     *
     * @param volume the new volume
     */
    public void setVolume(String volume) {
        this.volume = volume;
    }

    /**
     * Gets the number.
     *
     * @return the number
     */
    public String getNumber() {
        return number;
    }

    /**
     * Sets the number.
     *
     * @param number the new number
     */
    public void setNumber(String number) {
        this.number = number;
    }

    /**
     * Gets the month.
     *
     * @return the month
     */
    public String getMonth() {
        return month;
    }

    /**
     * Sets the month.
     *
     * @param month the new month
     */
    public void setMonth(String month) {
        this.month = month;
    }

    /**
     * Gets the url.
     *
     * @return the url
     */
    public String getUrl() {
        return url;
    }

    /**
     * Sets the url.
     *
     * @param url the new url
     */
    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * Gets the ee.
     *
     * @return the ee
     */
    public String getEe() {
        return ee;
    }

    /**
     * Sets the ee.
     *
     * @param ee the new ee
     */
    public void setEe(String ee) {
        this.ee = ee;
    }

    /**
     * Gets the cdrom.
     *
     * @return the cdrom
     */
    public String getCdrom() {
        return cdrom;
    }

    /**
     * Sets the cdrom.
     *
     * @param cdrom the new cdrom
     */
    public void setCdrom(String cdrom) {
        this.cdrom = cdrom;
    }

    /**
     * Gets the citations.
     *
     * @return the citations
     */
    public List<String> getCitations() {
        return citations;
    }

    /**
     * Sets the citations.
     *
     * @param citations the new citations
     */
    public void setCitations(List<String> citations) {
        this.citations = citations;
    }

    /**
     * Gets the publisher.
     *
     * @return the publisher
     */
    public String getPublisher() {
        return publisher;
    }

    /**
     * Sets the publisher.
     *
     * @param publisher the new publisher
     */
    public void setPublisher(String publisher) {
        this.publisher = publisher;
    }

    /**
     * Gets the note.
     *
     * @return the note
     */
    public String getNote() {
        return note;
    }

    /**
     * Sets the note.
     *
     * @param note the new note
     */
    public void setNote(String note) {
        this.note = note;
    }

    /**
     * Gets the crossref.
     *
     * @return the crossref
     */
    public String getCrossref() {
        return crossref;
    }

    /**
     * Sets the crossref.
     *
     * @param crossref the new crossref
     */
    public void setCrossref(String crossref) {
        this.crossref = crossref;
    }

    /**
     * Gets the isbn.
     *
     * @return the isbn
     */
    public String getIsbn() {
        return isbn;
    }

    /**
     * Sets the isbn.
     *
     * @param isbn the new isbn
     */
    public void setIsbn(String isbn) {
        this.isbn = isbn;
    }

    /**
     * Gets the series.
     *
     * @return the series
     */
    public String getSeries() {
        return series;
    }

    /**
     * Sets the series.
     *
     * @param series the new series
     */
    public void setSeries(String series) {
        this.series = series;
    }

    /**
     * Gets the school.
     *
     * @return the school
     */
    public String getSchool() {
        return school;
    }

    /**
     * Sets the school.
     *
     * @param school the new school
     */
    public void setSchool(String school) {
        this.school = school;
    }

    /**
     * Gets the chapter.
     *
     * @return the chapter
     */
    public String getChapter() {
        return chapter;
    }

    /**
     * Sets the chapter.
     *
     * @param chapter the new chapter
     */
    public void setChapter(String chapter) {
        this.chapter = chapter;
    }
}


text:
/***********************************************************************/
/*                                                                     */
/*                                OCaml                                */
/*                                                                     */
/*            Xavier Leroy, projet Cristal, INRIA Rocquencourt         */
/*                                                                     */
/*  Copyright 1997 Institut National de Recherche en Informatique et   */
/*  en Automatique.  All rights reserved.  This file is distributed    */
/*  under the terms of the GNU Library General Public License, with    */
/*  the special exception on linking described in file ../../LICENSE.  */
/*                                                                     */
/***********************************************************************/

int main()
{
#ifdef __STDC__
  return 0;
#else
  return 1;
#endif
}