text:
package org.broadinstitute.sting.gatk.traversals;

import org.apache.log4j.Logger;
import org.broadinstitute.sting.gatk.WalkerManager;
import org.broadinstitute.sting.gatk.contexts.AlignmentContext;
import org.broadinstitute.sting.gatk.contexts.ReferenceContext;
import org.broadinstitute.sting.gatk.datasources.providers.*;
import org.broadinstitute.sting.gatk.refdata.RefMetaDataTracker;
import org.broadinstitute.sting.gatk.walkers.*;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.GenomeLocSortedSet;
import org.broadinstitute.sting.utils.activeregion.ActiveRegion;
import org.broadinstitute.sting.utils.pileup.PileupElement;
import org.broadinstitute.sting.utils.sam.GATKSAMRecord;

import java.util.*;

/**
 * Created by IntelliJ IDEA.
 * User: rpoplin
 * Date: 12/9/11
 */

public class TraverseActiveRegions <M,T> extends TraversalEngine<M,T,ActiveRegionWalker<M,T>,LocusShardDataProvider> {
    /**
     * our log, which we want to capture anything from this class
     */
    protected static Logger logger = Logger.getLogger(TraversalEngine.class);

    private final Queue<ActiveRegion> workQueue = new LinkedList<ActiveRegion>();
    private final LinkedHashSet<GATKSAMRecord> myReads = new LinkedHashSet<GATKSAMRecord>();

    @Override
    protected String getTraversalType() {
        return "active regions";
    }

    @Override
    public T traverse( final ActiveRegionWalker<M,T> walker,
                       final LocusShardDataProvider dataProvider,
                       T sum) {
        logger.debug(String.format("TraverseActiveRegion.traverse: Shard is %s", dataProvider));

        final LocusView locusView = getLocusView( walker, dataProvider );
        final GenomeLocSortedSet initialIntervals = engine.getIntervals(); // BUGBUG: unfortunate inefficiency that needs to be removed

        final LocusReferenceView referenceView = new LocusReferenceView( walker, dataProvider );
        final int activeRegionExtension = walker.getClass().getAnnotation(ActiveRegionExtension.class).extension();

        if ( locusView.hasNext() ) { // trivial optimization to avoid unnecessary processing when there's nothing here at all

            int minStart = Integer.MAX_VALUE;
            final ArrayList<Double> isActiveList = new ArrayList<Double>();
            GenomeLoc firstIsActiveStart = null;

            //ReferenceOrderedView referenceOrderedDataView = new ReferenceOrderedView( dataProvider );
            ReferenceOrderedView referenceOrderedDataView = null;
            if ( WalkerManager.getWalkerDataSource(walker) != DataSource.REFERENCE_ORDERED_DATA )
                referenceOrderedDataView = new ManagingReferenceOrderedView( dataProvider );
            else
                referenceOrderedDataView = (RodLocusView)locusView;

            // We keep processing while the next reference location is within the interval
            GenomeLoc prevLoc = null;
            while( locusView.hasNext() ) {
                final AlignmentContext locus = locusView.next();
                GenomeLoc location = locus.getLocation();
                if(prevLoc != null) {
                    for(int iii = prevLoc.getStart() + 1; iii < location.getStart(); iii++ ) {
                        final GenomeLoc fakeLoc = engine.getGenomeLocParser().createGenomeLoc(prevLoc.getContig(), iii, iii);
                        if( initialIntervals == null || initialIntervals.overlaps( fakeLoc ) ) {
                            final double isActiveProb = ( walker.presetActiveRegions == null ? 0.0 : ( walker.presetActiveRegions.overlaps(fakeLoc) ? 1.0 : 0.0 ) );
                            isActiveList.add( isActiveProb );
                            if( firstIsActiveStart == null ) {
                                firstIsActiveStart = fakeLoc;
                            }
                        }
                    }
                }

                dataProvider.getShard().getReadMetrics().incrementNumIterations();

                // create reference context. Note that if we have a pileup of "extended events", the context will
                // hold the (longest) stretch of deleted reference bases (if deletions are present in the pileup).
                final ReferenceContext refContext = referenceView.getReferenceContext(location);

                // Iterate forward to get all reference ordered data covering this location
                final RefMetaDataTracker tracker = referenceOrderedDataView.getReferenceOrderedDataAtLocus(locus.getLocation(), refContext);

                // Call the walkers isActive function for this locus and add them to the list to be integrated later
                if( initialIntervals == null || initialIntervals.overlaps( location ) ) {
                    final double isActiveProb = ( walker.presetActiveRegions == null ? walker.isActive( tracker, refContext, locus )
                                                                                : ( walker.presetActiveRegions.overlaps(location) ? 1.0 : 0.0 ) );
                    isActiveList.add( isActiveProb );
                    if( firstIsActiveStart == null ) {
                        firstIsActiveStart = location;
                    }
                }

                // Grab all the previously unseen reads from this pileup and add them to the massive read list
                for( final PileupElement p : locus.getBasePileup() ) {
                    final GATKSAMRecord read = p.getRead();
                    if( !myReads.contains(read) ) {
                        myReads.add(read);
                    }
                }

                // If this is the last pileup for this shard calculate the minimum alignment start so that we know
                // which active regions in the work queue are now safe to process
                if( !locusView.hasNext() ) {
                    for( final PileupElement p : locus.getBasePileup() ) {
                        final GATKSAMRecord read = p.getRead();
                        if( !myReads.contains(read) ) {
                            myReads.add(read);
                        }
                        if( read.getAlignmentStart() < minStart ) { minStart = read.getAlignmentStart(); }
                    }
                }
                prevLoc = location;
                printProgress(dataProvider.getShard(), locus.getLocation());
            }

            // Take the individual isActive calls and integrate them into contiguous active regions and
            // add these blocks of work to the work queue
            final ArrayList<ActiveRegion> activeRegions = integrateActiveList( isActiveList, firstIsActiveStart, activeRegionExtension, walker.presetActiveRegions != null );
            logger.debug("Integrated " + isActiveList.size() + " isActive calls into " + activeRegions.size() + " regions." );
            if( walker.activeRegionOutStream == null ) {
                workQueue.addAll( activeRegions );
            } else { // Just want to output the active regions to a file, not actually process them
                for( final ActiveRegion activeRegion : activeRegions ) {
                    if( activeRegion.isActive ) {
                        walker.activeRegionOutStream.println( activeRegion.getLocation() );
                    }
                }
            }

            // Since we've traversed sufficiently past this point (or this contig!) in the workQueue we can unload those regions and process them
            while( workQueue.peek() != null && (workQueue.peek().getExtendedLoc().getStop() < minStart || !workQueue.peek().getExtendedLoc().getContig().equals(dataProvider.getLocus().getContig())) ) {
                final ActiveRegion activeRegion = workQueue.remove();
                sum = processActiveRegion( activeRegion, myReads, workQueue, sum, walker );
            }
        }

        return sum;
    }

    // Special function called in LinearMicroScheduler to empty out the work queue. Ugly for now but will be cleaned up when we push this functionality more into the engine
    public T endTraversal( final Walker<M,T> walker, T sum) {
        while( workQueue.peek() != null ) {
            final ActiveRegion activeRegion = workQueue.remove();
            sum = processActiveRegion( activeRegion, myReads, workQueue, sum, (ActiveRegionWalker<M,T>) walker );
        }

        return sum;
    }

    private T processActiveRegion( final ActiveRegion activeRegion, final LinkedHashSet<GATKSAMRecord> reads, final Queue<ActiveRegion> workQueue, final T sum, final ActiveRegionWalker<M,T> walker ) {
        final ArrayList<GATKSAMRecord> placedReads = new ArrayList<GATKSAMRecord>();
        for( final GATKSAMRecord read : reads ) {
            final GenomeLoc readLoc = this.engine.getGenomeLocParser().createGenomeLoc( read );
            if( activeRegion.getLocation().overlapsP( readLoc ) ) {
                // The region which the highest amount of overlap is chosen as the primary region for the read (tie breaking is done as right most region)
                long maxOverlap = activeRegion.getLocation().sizeOfOverlap( readLoc );
                ActiveRegion bestRegion = activeRegion;
                for( final ActiveRegion otherRegionToTest : workQueue ) {
                    if( otherRegionToTest.getLocation().sizeOfOverlap(readLoc) >= maxOverlap ) {
                        maxOverlap = otherRegionToTest.getLocation().sizeOfOverlap( readLoc );
                        bestRegion = otherRegionToTest;
                    }
                }
                bestRegion.add( read );

                // The read is also added to all other regions in which it overlaps but marked as non-primary
                if( walker.wantsNonPrimaryReads() ) {
                    if( !bestRegion.equals(activeRegion) ) {
                        activeRegion.add( read );
                    }
                    for( final ActiveRegion otherRegionToTest : workQueue ) {
                        if( !bestRegion.equals(otherRegionToTest) && otherRegionToTest.getExtendedLoc().overlapsP( readLoc ) ) {
                            otherRegionToTest.add( read );
                        }
                    }
                }
                placedReads.add( read );
            } else if( activeRegion.getExtendedLoc().overlapsP( readLoc ) && walker.wantsNonPrimaryReads() ) {
                activeRegion.add( read );
            }
        }
        reads.removeAll( placedReads ); // remove all the reads which have been placed into their active region

        logger.debug(">> Map call with " + activeRegion.getReads().size() + " " + (activeRegion.isActive ? "active" : "inactive") + " reads @ " + activeRegion.getLocation() + " with full extent: " + activeRegion.getReferenceLoc());
        final M x = walker.map( activeRegion, null );
        return walker.reduce( x, sum );
    }

    /**
     * Gets the best view of loci for this walker given the available data.
     * @param walker walker to interrogate.
     * @param dataProvider Data which which to drive the locus view.
     * @return A view of the locus data, where one iteration of the locus view maps to one iteration of the traversal.
     */
    private LocusView getLocusView( final Walker<M,T> walker, final LocusShardDataProvider dataProvider ) {
        final DataSource dataSource = WalkerManager.getWalkerDataSource(walker);
        if( dataSource == DataSource.READS )
            return new CoveredLocusView(dataProvider);
        else if( dataSource == DataSource.REFERENCE ) //|| ! GenomeAnalysisEngine.instance.getArguments().enableRodWalkers )
            return new AllLocusView(dataProvider);
        else if( dataSource == DataSource.REFERENCE_ORDERED_DATA )
            return new RodLocusView(dataProvider);
        else
            throw new UnsupportedOperationException("Unsupported traversal type: " + dataSource);
    }

    // band-pass filter the list of isActive probabilities and turn into active regions
    private ArrayList<ActiveRegion> integrateActiveList( final ArrayList<Double> activeList, final GenomeLoc firstIsActiveStart, final int activeRegionExtension, final boolean presetRegions ) {

        final double ACTIVE_PROB_THRESHOLD = 0.2; // BUGBUG: needs to be set-able by the walker author
        final ArrayList<ActiveRegion> returnList = new ArrayList<ActiveRegion>();
        if( activeList.size() == 0 ) {
            return returnList;
        } else if( activeList.size() == 1 ) {
            returnList.add( new ActiveRegion( engine.getGenomeLocParser().createGenomeLoc(firstIsActiveStart.getContig(), firstIsActiveStart.getStart(), firstIsActiveStart.getStart()),
                    activeList.get(0) > ACTIVE_PROB_THRESHOLD, engine.getGenomeLocParser(), activeRegionExtension ) );
            return returnList;
        } else {
            final Double[] activeProbArray = activeList.toArray(new Double[activeList.size()]);
            final double[] filteredProbArray = new double[activeProbArray.length];
            final int FILTER_SIZE = ( presetRegions ? 0 : 50 ); // BUGBUG: needs to be set-able by the walker author
            final int MAX_ACTIVE_REGION = ( presetRegions ? 16001 : 425 ); // BUGBUG: needs to be set-able by the walker author
            for( int iii = 0; iii < activeProbArray.length; iii++ ) {
                double maxVal = 0;
                for( int jjj = Math.max(0, iii-FILTER_SIZE); jjj < Math.min(activeList.size(), iii+FILTER_SIZE+1); jjj++ ) {
                    if( activeProbArray[jjj] > maxVal ) { maxVal = activeProbArray[jjj]; }
                }
                filteredProbArray[iii] = maxVal;
            }

            boolean curStatus = filteredProbArray[0] > ACTIVE_PROB_THRESHOLD;
            int curStart = 0;
            for(int iii = 1; iii < filteredProbArray.length; iii++ ) {
                final boolean thisStatus = filteredProbArray[iii] > ACTIVE_PROB_THRESHOLD;
                if( curStatus != thisStatus || (iii-curStart) > MAX_ACTIVE_REGION ) {
                    returnList.add( new ActiveRegion(
                            engine.getGenomeLocParser().createGenomeLoc(firstIsActiveStart.getContig(), firstIsActiveStart.getStart() + curStart, firstIsActiveStart.getStart() + (iii-1)),
                            curStatus, engine.getGenomeLocParser(), activeRegionExtension ) );
                    curStatus = thisStatus;
                    curStart = iii;
                }
            }
            if( curStart != filteredProbArray.length-1 ) {
                returnList.add( new ActiveRegion(
                        engine.getGenomeLocParser().createGenomeLoc(firstIsActiveStart.getContig(), firstIsActiveStart.getStart() + curStart, firstIsActiveStart.getStart() + (filteredProbArray.length-1)),
                        curStatus, engine.getGenomeLocParser(), activeRegionExtension ) );
            }
            return returnList;
        }
    }
}


text:
<?
	/****************************************************************************
	* Software distributed under the License is distributed on an "AS IS" 		*
	* basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See the 	*
	* License for a specific language governing rights and limitations under	*
	* the License. 																*
	* 																			*
	*	The Original Code is - InTerra Blog Machine   				            *
	* 																			*
	*	The Initial Developer of the Original Code is 							*
	* 																			*
	* 			Kulikov Alexey <alex [at] essentialmind [dot] com>	 			*
	* 																			*
	* 				All Rights Reserved // www.inses.ru							*
	* 																			*
	* Read the full license in the license.rtf file distributed along with		*
	* this software package.													*
	*****************************************************************************/

    //actions?
    if($_GET['do'] == 'delete' and $_SESSION['admin']){
        $db->query("DELETE FROM ".PREFIX."pages WHERE url = '".$_GET['section']."'");
        header("Location: ".SERVER_ROOT);
        exit;
    }

    $breadCrumbs[] = $page['title'];

	//get data and pass to smarty
    $smarty->assign("data",$page);

    //select smarty template
    $smarty->assign("template","page.htm");
?>

redpajama_set_name: RedPajamaGithub


text:
//---------------------------------------------------------------------------//

//---------------------------------------------------------------------------//
/*!
 * \file   tstPRNG.cpp
 * \author Stuart Slattery
 * \brief  PRNG class unit tests.
 */
//---------------------------------------------------------------------------//

#include <random>
#include <iostream>
#include <vector>
#include <cmath>
#include <sstream>
#include <stdexcept>

#include <MCLS_PRNG.hpp>
#include <MCLS_Xorshift.hpp>

#include "Teuchos_UnitTestHarness.hpp"
#include "Teuchos_RCP.hpp"
#include "Teuchos_Array.hpp"
#include "Teuchos_DefaultComm.hpp"
#include "Teuchos_CommHelpers.hpp"
#include "Teuchos_as.hpp"

//---------------------------------------------------------------------------//
// HELPER FUNCTIONS
//---------------------------------------------------------------------------//

// Get the default communicator.
template<class Ordinal>
Teuchos::RCP<const Teuchos::Comm<Ordinal> > getDefaultComm()
{
#ifdef HAVE_MPI
    return Teuchos::DefaultComm<Ordinal>::getComm();
#else
    return Teuchos::rcp(new Teuchos::SerialComm<Ordinal>() );
#endif
}

//---------------------------------------------------------------------------//
// Tests.
//---------------------------------------------------------------------------//
TEUCHOS_UNIT_TEST_TEMPLATE_1_DECL( PRNG, prng_test, RNG )
{
    Teuchos::RCP<const Teuchos::Comm<int> > comm = getDefaultComm<int>();

    MCLS::PRNG<RNG> prng( comm->getRank() );

    // Make a set of random numbers on each process.
    int num_random = 1000;
    Teuchos::Array<double> rands( num_random * comm->getSize(), 0.0 );
    std::uniform_real_distribution<double> rand_dist(0.0,1.0);
    for ( int i = 0; i < num_random; ++i )
    {
	rands[comm->getRank()*num_random + i] = prng.random( rand_dist );
    }

    // Collect all random numbers on each process.
    Teuchos::Array<double> global_rands( num_random * comm->getSize(), 0.0 );
    Teuchos::reduceAll<int,double>( *comm, Teuchos::REDUCE_SUM,
				    global_rands.size(),
				    rands.getRawPtr(), global_rands.getRawPtr() );

    // Check that the random numbers on each process are unique.
    for ( int i = 0; i < comm->getSize(); ++i )
    {
	for ( int j = 0; j < comm->getSize(); ++j )
	{
	    if ( i != j )
	    {
		for ( int k = 0; k < num_random; ++k )
		{
		    TEST_INEQUALITY( global_rands[i*num_random + k],
				     global_rands[j*num_random + k] );
		}
	    }
	}
    }
}

typedef std::mt19937 mt19937;
typedef std::mt19937_64 mt1993764;
typedef MCLS::Xorshift<> Xorshift;

TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( PRNG, prng_test, mt19937 )
TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( PRNG, prng_test, mt1993764 )
TEUCHOS_UNIT_TEST_TEMPLATE_1_INSTANT( PRNG, prng_test, Xorshift )

//---------------------------------------------------------------------------//
// end tstPRNG.cpp
//---------------------------------------------------------------------------//


text:
namespace FaceRecognizerBindings {
	struct NewWorker : public FF::SimpleWorker {
	public:
		int num_components = 0;
		double threshold = DBL_MAX;

		bool unwrapOptionalArgs(Nan::NAN_METHOD_ARGS_TYPE info) {
			return (
				FF::IntConverter::optArg(0, &num_components, info) ||
				FF::DoubleConverter::optArg(1, &threshold, info)
				);
		}

		bool hasOptArgsObject(Nan::NAN_METHOD_ARGS_TYPE info) {
			return FF::isArgObject(info, 0);
		}

		bool unwrapOptionalArgsFromOpts(Nan::NAN_METHOD_ARGS_TYPE info) {
			v8::Local<v8::Object> opts = info[0]->ToObject(Nan::GetCurrentContext()).ToLocalChecked();
			return (
				FF::IntConverter::optProp(&num_components, "num_components", opts) ||
				FF::DoubleConverter::optProp(&threshold, "threshold", opts)
				);
		}
	};

  struct TrainWorker : public CatchCvExceptionWorker {
  public:
    cv::Ptr<cv::face::FaceRecognizer> self;
    TrainWorker(cv::Ptr<cv::face::FaceRecognizer> self) {
      this->self = self;
    }

    std::vector<cv::Mat> images;
    std::vector<int> labels;

    std::string executeCatchCvExceptionWorker() {
      self->train(images, labels);
      return "";
    }

    bool unwrapRequiredArgs(Nan::NAN_METHOD_ARGS_TYPE info) {
      return (
        Mat::ArrayConverter::arg(0, &images, info) ||
        FF::IntArrayConverter::arg(1, &labels, info)
      );
    }
  };

  struct PredictWorker : public CatchCvExceptionWorker {
  public:
    cv::Ptr<cv::face::FaceRecognizer> self;
    PredictWorker(cv::Ptr<cv::face::FaceRecognizer> self) {
      this->self = self;
    }

    cv::Mat image;
    int label;
    double confidence;

    std::string executeCatchCvExceptionWorker() {
      self->predict(image, label, confidence);
      return "";
    }

    v8::Local<v8::Value> getReturnValue() {
      v8::Local<v8::Object> ret = Nan::New<v8::Object>();
      Nan::Set(ret, Nan::New("label").ToLocalChecked(), Nan::New(label));
      Nan::Set(ret, Nan::New("confidence").ToLocalChecked(), Nan::New(confidence));
      return ret;
    }

    bool unwrapRequiredArgs(Nan::NAN_METHOD_ARGS_TYPE info) {
      return (
        Mat::Converter::arg(0, &image, info)
      );
    }
  };

}

#endif


text:
"""
 (_) ___ _ __ ___  _ __ | |/ / \ | |/ _ \ / ___| |/ /
 | |/ __| '_ ` _ \| '_ \| ' /|  \| | | | | |   | ' /
 | | (__| | | | | | |_) | . \| |\  | |_| | |___| . \
 |_|\___|_| |_| |_| .__/|_|\_\_| \_|\___/ \____|_|\_\
                  |_| (c) by Victor Dorneanu

icmpKNOCK - ICMP port knocking server
Copyright (C) 2009-2010 by Victor Dorneanu

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.
"""

import socket
import time
import datetime
import sys
import os
import getopt
from modules import Listener
from modules.ActionsReader import *
from modules.ConfReader import *
from modules.Utils import *

# Default configuration file
config_file = "conf/icmpKNOCK.conf"

# Default actions file
actions_file = "conf/actions.conf"

# Global options
g_options = { 'daemon'  : True,
              'debug'   : False,
              'config'  : config_file,
              'actions' : actions_file
            }

# --- Main procedure
if __name__ == '__main__':

    # Print usage menu
    def usage():
        banner = "                                             \
        \n(_) ___ _ __ ___  _ __ | |/ / \ | |/ _ \ / ___| |/ / \
        \n| |/ __| '_ ` _ \| '_ \| ' /|  \| | | | | |   | ' /  \
        \n| | (__| | | | | | |_) | . \| |\  | |_| | |___| . \  \
        \n|_|\___|_| |_| |_| .__/|_|\_\_| \_|\___/ \____|_|\_\ \
        \n                 |_|     v0.2 (c) by Victor Dorneanu \
        \n                                                     \
        \nUsage:                                               \
        \n          -h  Show this help                         \
        \n          -d  Enable debug messages                  \
        \n          -f  Don't daemonize process                \
        \n          -c  Specify general config file            \
        \n              Default: %s                            \
        \n                                                     \
        \n          -a  Specify actions file (see README)      \
        \n              Default %s                             \
        \n                                                     \
        " % (config_file, actions_file)

        print banner

    try:

        # Get command line arguments
        opts, args = getopt.getopt(sys.argv[1:], "dfhvc:a:", ["help"])

        for o, a in opts:
            if o in ("-h", "--help"):
                usage()
                sys.exit(1)

            elif o == "-f":
                g_options['daemon'] = False

            elif o == "-d":
                g_options['debug'] = True

            elif o == "-c":
                g_options['config'] = a

            elif o == "-a":
                g_options['actions'] = a

            else:
                pass

        # Read config file
        if g_options['debug']:
            Utils.show_debug_msg(Utils.whoami(), "Reading conf file %s" % g_options['config'])

        conf = ConfReader(g_options['config'], g_options)
        conf_opts = conf.read_conf()

        # Read actions file
        if g_options['debug']:
            Utils.show_debug_msg(Utils.whoami(), "Reading actions file %s" % g_options['actions'])

        acts = ActionsReader(g_options['actions'], g_options)
        actions = acts.clean_actions(acts.read_actions())

        # Daemonize process
        if g_options['daemon']:

            # Debug
            if g_options['debug']:
                Utils.show_debug_msg(Utils.whoami(), "Create new child process and become a daemon")

            pid = os.fork()
            if pid > 0:
                # exit first parent
                sys.exit(1)

        # Activate ICMP listener
        listener = Listener.ICMPListener(actions, conf_opts, g_options)
        listener.go()

    except getopt.GetoptError, e:
        usage()
        print str(e)
        sys.exit(1)

    except OSError, e:
        print >>sys.stderr, "fork failed: %d (%s)" % (e.errno, e.strerror)
        sys.exit(1)

    except KeyboardInterrupt:
        exit('Aborting...')

# EOF


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using ProtoBuild.Types;
using ProtoBuild.XBDMarkup.Elements.Interfaces;

namespace ProtoBuild.XBDMarkup.Elements
{
    [ChildTypes(new Type[] { typeof(VariableDefinition) })]
    internal class RegistryLookup : XBDElement, IValueProvider
    {
        public String SubKey { get; set; }
        public RegistryItem RegistryItem { get; set; }
        private RegistryLookup()
            : base(null)
        {
        }
        public RegistryLookup(XBDDef def)
            : base(def)
        {
        }

        protected override void Parse(XBDElement parent, XmlReader reader)
        {
            while (reader.MoveToNextAttribute())
            {
                if (reader.Name == "key")
                {
                    this.RegistryItem = new RegistryItem(reader.Value, this.XBDDef.Builder, false);
                }
                if (reader.Name == "subkey")
                {
                    this.SubKey = reader.Value;
                }
            }
        }
        public override void Build(XBDElement parent)
        {

        }

        public string ProvideValue()
        {
            if (RegistryItem.IsNull(SubKey))
                return null;
            else
                return (string)RegistryItem.GetValue(this.SubKey);
        }
        public bool HasValue()
        {
            return !(RegistryItem.IsNull(SubKey));
        }
    }
}


text:
package com.affablebean.entity1;

public class OrderedProduct {

	private final Long customerOrderId;
	private final Long productId;
	private final Integer quantity;

	public OrderedProduct(Long customerOrderId, Long productId, Integer quantity) {
		this.customerOrderId = customerOrderId;
		this.productId = productId;
		this.quantity = quantity;
	}

	public Long getCustomerOrderId() {
		return customerOrderId;
	}

	public Long getProductId() {
		return productId;
	}

	public Integer getQuantity() {
		return quantity;
	}

	@Override
	public String toString() {
		return "OrderedProduct{" + "customerOrderId=" + customerOrderId
						+ ", productId=" + productId + ", quantity=" + quantity + '}';
	}

}


text:
{-- snippet all --}
import Control.Exception

handler :: ArithException -> IO ()
handler e = putStrLn $ "Caught arithmetic error: " ++ show e

safePrint :: Integer -> IO ()
safePrint x = handleJust arithExceptions handler (print x)
{-- /snippet all --}


text:
package org.apache.flink.runtime.state;

import org.apache.flink.api.common.ExecutionConfig;
import org.apache.flink.api.common.JobID;
import org.apache.flink.api.common.state.ListState;
import org.apache.flink.api.common.state.ListStateDescriptor;
import org.apache.flink.api.common.state.ValueState;
import org.apache.flink.api.common.state.ValueStateDescriptor;
import org.apache.flink.api.common.typeutils.TypeSerializerSerializationUtil;
import org.apache.flink.api.common.typeutils.base.IntSerializer;
import org.apache.flink.core.memory.DataInputViewStreamWrapper;
import org.apache.flink.runtime.checkpoint.CheckpointOptions;
import org.apache.flink.runtime.execution.Environment;
import org.apache.flink.runtime.state.heap.HeapKeyedStateBackend;
import org.apache.flink.runtime.state.memory.MemoryStateBackend;
import org.apache.flink.util.FutureUtil;
import org.junit.Assert;
import org.junit.Ignore;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.Serializable;
import java.util.Collections;
import java.util.HashMap;
import java.util.concurrent.RunnableFuture;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import static org.mockito.Matchers.any;
import static org.mockito.Mockito.doThrow;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;

/**
 * Tests for the {@link org.apache.flink.runtime.state.memory.MemoryStateBackend}.
 */
@RunWith(PowerMockRunner.class)
@PrepareForTest(TypeSerializerSerializationUtil.class)
public class MemoryStateBackendTest extends StateBackendTestBase<MemoryStateBackend> {

	@Override
	protected MemoryStateBackend getStateBackend() throws Exception {
		return new MemoryStateBackend(useAsyncMode());
	}

	protected boolean useAsyncMode() {
		return false;
	}

	// disable these because the verification does not work for this state backend
	@Override
	@Test
	public void testValueStateRestoreWithWrongSerializers() {}

	@Override
	@Test
	public void testListStateRestoreWithWrongSerializers() {}

	@Override
	@Test
	public void testReducingStateRestoreWithWrongSerializers() {}

	@Override
	@Test
	public void testMapStateRestoreWithWrongSerializers() {}

	@Test
	public void testOversizedState() {
		try {
			MemoryStateBackend backend = new MemoryStateBackend(10);
			CheckpointStreamFactory streamFactory = backend.createStreamFactory(new JobID(), "test_op");

			HashMap<String, Integer> state = new HashMap<>();
			state.put("hey there", 2);
			state.put("the crazy brown fox stumbles over a sentence that does not contain every letter", 77);

			try {
				CheckpointStreamFactory.CheckpointStateOutputStream outStream =
						streamFactory.createCheckpointStateOutputStream(12, 459);

				ObjectOutputStream oos = new ObjectOutputStream(outStream);
				oos.writeObject(state);

				oos.flush();

				outStream.closeAndGetHandle();

				fail("this should cause an exception");
			}
			catch (IOException e) {
				// now darling, isn't that exactly what we wanted?
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	@Test
	public void testStateStream() {
		try {
			MemoryStateBackend backend = new MemoryStateBackend();
			CheckpointStreamFactory streamFactory = backend.createStreamFactory(new JobID(), "test_op");

			HashMap<String, Integer> state = new HashMap<>();
			state.put("hey there", 2);
			state.put("the crazy brown fox stumbles over a sentence that does not contain every letter", 77);

			CheckpointStreamFactory.CheckpointStateOutputStream os = streamFactory.createCheckpointStateOutputStream(1, 2);
			ObjectOutputStream oos = new ObjectOutputStream(os);
			oos.writeObject(state);
			oos.flush();
			StreamStateHandle handle = os.closeAndGetHandle();

			assertNotNull(handle);

			try (ObjectInputStream ois = new ObjectInputStream(handle.openInputStream())) {
				assertEquals(state, ois.readObject());
				assertTrue(ois.available() <= 0);
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	@Test
	public void testOversizedStateStream() {
		try {
			MemoryStateBackend backend = new MemoryStateBackend(10);
			CheckpointStreamFactory streamFactory = backend.createStreamFactory(new JobID(), "test_op");

			HashMap<String, Integer> state = new HashMap<>();
			state.put("hey there", 2);
			state.put("the crazy brown fox stumbles over a sentence that does not contain every letter", 77);

			CheckpointStreamFactory.CheckpointStateOutputStream os = streamFactory.createCheckpointStateOutputStream(1, 2);
			ObjectOutputStream oos = new ObjectOutputStream(os);

			try {
				oos.writeObject(state);
				oos.flush();
				os.closeAndGetHandle();
				fail("this should cause an exception");
			}
			catch (IOException e) {
				// oh boy! what an exception!
			}
		}
		catch (Exception e) {
			e.printStackTrace();
			fail(e.getMessage());
		}
	}

	/**
	 * Verifies that the operator state backend fails with appropriate error and message if
	 * previous serializer can not be restored.
	 */
	@Test
	public void testOperatorStateRestoreFailsIfSerializerDeserializationFails() throws Exception {
		AbstractStateBackend abstractStateBackend = new MemoryStateBackend(4096);

		Environment env = mock(Environment.class);
		when(env.getExecutionConfig()).thenReturn(new ExecutionConfig());
		when(env.getUserClassLoader()).thenReturn(OperatorStateBackendTest.class.getClassLoader());

		OperatorStateBackend operatorStateBackend = abstractStateBackend.createOperatorStateBackend(env, "test-op-name");

		// write some state
		ListStateDescriptor<Serializable> stateDescriptor1 = new ListStateDescriptor<>("test1", new JavaSerializer<>());
		ListStateDescriptor<Serializable> stateDescriptor2 = new ListStateDescriptor<>("test2", new JavaSerializer<>());
		ListStateDescriptor<Serializable> stateDescriptor3 = new ListStateDescriptor<>("test3", new JavaSerializer<>());
		ListState<Serializable> listState1 = operatorStateBackend.getListState(stateDescriptor1);
		ListState<Serializable> listState2 = operatorStateBackend.getListState(stateDescriptor2);
		ListState<Serializable> listState3 = operatorStateBackend.getUnionListState(stateDescriptor3);

		listState1.add(42);
		listState1.add(4711);

		listState2.add(7);
		listState2.add(13);
		listState2.add(23);

		listState3.add(17);
		listState3.add(18);
		listState3.add(19);
		listState3.add(20);

		CheckpointStreamFactory streamFactory = abstractStateBackend.createStreamFactory(new JobID(), "testOperator");
		RunnableFuture<OperatorStateHandle> runnableFuture =
			operatorStateBackend.snapshot(1, 1, streamFactory, CheckpointOptions.forCheckpoint());
		OperatorStateHandle stateHandle = FutureUtil.runIfNotDoneAndGet(runnableFuture);

		try {

			operatorStateBackend.close();
			operatorStateBackend.dispose();

			operatorStateBackend = abstractStateBackend.createOperatorStateBackend(
				env,
				"testOperator");

			// mock failure when deserializing serializer
			TypeSerializerSerializationUtil.TypeSerializerSerializationProxy<?> mockProxy =
					mock(TypeSerializerSerializationUtil.TypeSerializerSerializationProxy.class);
			doThrow(new IOException()).when(mockProxy).read(any(DataInputViewStreamWrapper.class));
			PowerMockito.whenNew(TypeSerializerSerializationUtil.TypeSerializerSerializationProxy.class).withAnyArguments().thenReturn(mockProxy);

			operatorStateBackend.restore(Collections.singletonList(stateHandle));

			fail("The operator state restore should have failed if the previous state serializer could not be loaded.");
		} catch (IOException expected) {
			Assert.assertTrue(expected.getMessage().contains("Unable to restore operator state"));
		} finally {
			stateHandle.discardState();
		}
	}

	/**
	 * Verifies that memory-backed keyed state backend fails with appropriate error and message if
	 * previous serializer can not be restored.
	 */
	@Test
	public void testKeyedStateRestoreFailsIfSerializerDeserializationFails() throws Exception {
		CheckpointStreamFactory streamFactory = createStreamFactory();
		KeyedStateBackend<Integer> backend = createKeyedBackend(IntSerializer.INSTANCE);

		ValueStateDescriptor<String> kvId = new ValueStateDescriptor<>("id", String.class, null);
		kvId.initializeSerializerUnlessSet(new ExecutionConfig());

		HeapKeyedStateBackend<Integer> heapBackend = (HeapKeyedStateBackend<Integer>) backend;

		assertEquals(0, heapBackend.numStateEntries());

		ValueState<String> state = backend.getPartitionedState(VoidNamespace.INSTANCE, VoidNamespaceSerializer.INSTANCE, kvId);

		// write some state
		backend.setCurrentKey(0);
		state.update("hello");
		state.update("ciao");

		KeyedStateHandle snapshot = runSnapshot(((HeapKeyedStateBackend<Integer>) backend).snapshot(
			682375462378L,
			2,
			streamFactory,
			CheckpointOptions.forCheckpoint()));

		backend.dispose();

		// ========== restore snapshot ==========

		Environment env = mock(Environment.class);
		when(env.getExecutionConfig()).thenReturn(new ExecutionConfig());
		when(env.getUserClassLoader()).thenReturn(OperatorStateBackendTest.class.getClassLoader());

		// mock failure when deserializing serializer
		TypeSerializerSerializationUtil.TypeSerializerSerializationProxy<?> mockProxy =
				mock(TypeSerializerSerializationUtil.TypeSerializerSerializationProxy.class);
		doThrow(new IOException()).when(mockProxy).read(any(DataInputViewStreamWrapper.class));
		PowerMockito.whenNew(TypeSerializerSerializationUtil.TypeSerializerSerializationProxy.class).withAnyArguments().thenReturn(mockProxy);

		try {
			restoreKeyedBackend(IntSerializer.INSTANCE, snapshot, env);

			fail("The keyed state restore should have failed if the previous state serializer could not be loaded.");
		} catch (IOException expected) {
			Assert.assertTrue(expected.getMessage().contains("Unable to restore keyed state"));
		}
	}

	@Ignore
	@Test
	public void testConcurrentMapIfQueryable() throws Exception {
		super.testConcurrentMapIfQueryable();
	}
}


text:
package com.db4o.internal;

/**
 * @exclude
 */
public interface CommittedCallbackDispatcher {

	boolean willDispatchCommitted();

	void dispatchCommitted(CallbackObjectInfoCollections committedInfo);
}


text:
cd "${BASH_SOURCE%/*}/.."

echo "Ensuring all submodules are checked out and up to date..."
git submodule init
git submodule sync
git submodule update

# Rebase master by default
git config rebase.stat true
git config branch.master.rebase true

echo "Checking basic user information..."
Scripts/GitSetup/setup-user
echo

Scripts/GitSetup/setup-hooks
echo

echo "Setting up git aliases..."
Scripts/setup-git-aliases
echo

echo "Setting up Gerrit..."
Scripts/GitSetup/setup-gerrit ||
  echo "Failed to setup Gerrit. Run this script again to retry."
echo

setup_version=1
git config hooks.setup ${setup_version}

echo "Setup for development complete for ParaViewSuperbuild."


text:
layout: post
episodeNumber: 235
guest: Brent Stineman
guestImage: brent-stineman.jpg
title: Ignite 2019
date: 2019-11-17
audioUrl: https://static.msdevshow.com/episodes/msdevshow_0235.mp3
---

### News

 - [Ignite 2019 Book of News](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf)

## Brent Stineman

Principal Engineer at Microsoft

- [@brentcodemonkey](https://twitter.com/brentcodemonkey)
- [brentdacodemonkey blog](https://brentdacodemonkey.wordpress.com/)

### Ignite 2019

 - [Azure Arc](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=11&zoom=100,0,0) - impact on hybrid cloud and intelligent workspaces for the changing needs for increasingly mobile workforce
 - [Azure Data Services](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=11&zoom=100,0,0) - run anywhere… Arc+Containers make workloads highly portable
 - [Gen2 VMs](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=11&zoom=100,0,0) GA'd - UEFI (Unified Extended Firmware Interface) boot options! No more BIOS. More control over firmware level operations.
 - [Azure Bastion GA](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=13&zoom=100,0,0) - secure, seemless RDP/SSH to cloud VMs
 - [Azure Disk CMK (Customer Managed Keys)](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=15&zoom=100,0,0) - encrypt your Azure VM disks using keys you manage.
 - [Event Hubs on Azure Stack (preview)](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=21&zoom=100,0,0) - power of Kafka on-prem as a managed solution Azure Security Center + Logic Apps - workflows that leverage Logic apps?
 - [Azure Functions Premium](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=31&zoom=100,0,0) - improved cold start and serverless automation.
 - [Azure SQL Database Edge](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=42&zoom=100,0,0) - SQL in a container at the edge?
 - [Azure Quantum](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=46&zoom=100,0,0) - death of traditional mathematical encryption? Controlling 50k qubits through 3 wires. This "topological qubit" approach is significantly different then Google's Quantum Supremacy approach.
   - [For faster quantum computing, Microsoft builds a better qubit](https://www.cnet.com/news/for-faster-quantum-computing-microsoft-builds-a-better-qubit/)
   - [The Q# Programming Language](https://docs.microsoft.com/en-us/quantum/language/?view=qsharp-preview)
 - [VisualStudio Online preview ](https://news.microsoft.com/wp-content/uploads/prod/sites/563/2019/11/Ignite-2019-Book-of-News.pdf#page=36&zoom=100,0,0)
   - [online.visualstudio.com](https://online.visualstudio.com/login)


text:
export const credentialParams = {
  mode: 'cors',
  credentials: 'include',
};


text:
// This is an open source non-commercial project. Dear PVS-Studio, please check it.
// PVS-Studio Static Code Analyzer for C, C++ and C#: http://www.viva64.com

/* FileOutput.cs -- файловый вывод
 */

#region

using System;
using System.IO;
using System.Text;

#endregion

namespace ManagedClient.Output
{
    /// <summary>
    /// Файловый вывод.
    /// </summary>
    public sealed class FileOutput
        : AbstractOutput
    {
        #region Properties

        /// <summary>
        /// Имя файла.
        /// </summary>
        public string FileName { get { return _fileName; } }

        #endregion

        #region Construction

        /// <summary>
        /// Конструктор.
        /// </summary>
        public FileOutput()
        {
        }

        /// <summary>
        /// Конструктор.
        /// </summary>
        public FileOutput
            (
                string fileName
            )
        {
            Open
                (
                    fileName
                );
        }

        #endregion

        #region Private members

        private string _fileName;

        private TextWriter _writer;

        #endregion

        #region Public methods

        /// <summary>
        /// Закрытие файла.
        /// </summary>
        public void Close()
        {
            Dispose();
        }

        /// <summary>
        /// Открытие файла.
        /// </summary>
        public void Open
            (
                string fileName,
                bool append
            )
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName");
            }
            Close();
            _fileName = fileName;
            _writer = new StreamWriter
                (
                    fileName,
                    append
                );
        }

        /// <summary>
        /// Открытие файла.
        /// </summary>
        public void Open
            (
                string fileName
            )
        {
            Open
                (
                    fileName,
                    false
                );
        }

        /// <summary>
        /// Открытие файла.
        /// </summary>
        public void Open
            (
                string fileName,
                bool append,
                Encoding encoding
            )
        {
            if (string.IsNullOrEmpty(fileName))
            {
                throw new ArgumentNullException("fileName");
            }
            if (ReferenceEquals(encoding, null))
            {
                throw new ArgumentNullException("encoding");
            }
            Close();
            _fileName = fileName;
            _writer = new StreamWriter
                (
                    fileName,
                    append,
                    encoding
                );
        }

        /// <summary>
        /// Открытие файла.
        /// </summary>
        public void Open
            (
                string fileName,
                Encoding encoding
            )
        {
            Open
                (
                    fileName,
                    false,
                    encoding
                );
        }

        #endregion

        #region AbstractOutput members

        /// <summary>
        /// Флаг: был ли вывод с помощью WriteError.
        /// </summary>
        /// <value><c>true</c> if [have error]; otherwise, <c>false</c>.</value>
        public override bool HaveError { get; set; }

        /// <summary>
        /// Очищает вывод, например, окно.
        /// Надо переопределить в потомке.
        /// </summary>
        /// <returns>AbstractOutput.</returns>
        public override AbstractOutput Clear()
        {
            // TODO: implement properly
            return this;
        }

        /// <summary>
        /// Конфигурирование объекта.
        /// Надо переопределить в потомке.
        /// </summary>
        /// <param name="configuration">The configuration.</param>
        /// <returns>AbstractOutput.</returns>
        public override AbstractOutput Configure
            (
                string configuration
            )
        {
            // TODO: implement properly
            Open(configuration);
            return this;
        }

        /// <summary>
        /// Метод, который нужно переопределить
        /// в потомке.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns>Возвращает сам объект
        /// вывода.</returns>
        public override AbstractOutput Write
            (
                string text
            )
        {
            if (!ReferenceEquals(_writer, null))
            {
                _writer.Write(text);
                _writer.Flush();
            }
            return this;
        }

        /// <summary>
        /// Выводит ошибку. Например, красным цветом.
        /// Надо переопределить в потомке.
        /// </summary>
        /// <param name="text">The text.</param>
        /// <returns>AbstractOutput.</returns>
        public override AbstractOutput WriteError
            (
                string text
            )
        {
            HaveError = true;
            if (!ReferenceEquals(_writer, null))
            {
                _writer.Write(text);
                _writer.Flush();
            }
            return this;
        }

        #endregion

        #region IDisposable members

        /// <summary>
        /// Disposes this instance.
        /// </summary>
        public override void Dispose()
        {
            if (_writer != null)
            {
                _writer.Dispose();
                _writer = null;
            }
            base.Dispose();
        }

        #endregion
    }
}


text:
<!DOCTYPE html>

  <title>Sample Angular App with Auth0</title>

      click to login

      main
      logout

{{message}}


text:
<?php

namespace Omnipay\Vindicia;

use Omnipay\Tests\GatewayTestCase;
use Omnipay\Omnipay;
use Omnipay\Vindicia\TestFramework\DataFaker;
use Omnipay\Vindicia\Message\AuthorizeRequest;

class GatewayTest extends GatewayTestCase
{
    /**
     * @return void
     */
    public function setUp()
    {
        date_default_timezone_set('Europe/London');
        $this->gateway = new Gateway($this->getHttpClient(), $this->getHttpRequest());
        $this->gateway->setTestMode(true);
        $this->faker = new DataFaker();
    }

    /**
     * @return void
     */
    public function testGetName()
    {
        $this->assertSame('Vindicia', $this->gateway->getName());
    }

    /**
     * @return void
     */
    public function testCreation()
    {
        $gateway = Omnipay::create('Vindicia');
        $this->assertInstanceOf('Omnipay\Vindicia\Gateway', $gateway);
    }

    /**
     * @return void
     */
    public function testUsername()
    {
        $username = $this->faker->username();

        $this->assertSame($this->gateway, $this->gateway->setUsername($username));
        $this->assertSame($username, $this->gateway->getUsername());
    }

    /**
     * @return void
     */
    public function testPassword()
    {
        $password = $this->faker->password();

        $this->assertSame($this->gateway, $this->gateway->setPassword($password));
        $this->assertSame($password, $this->gateway->getPassword());
    }

    /**
     * @return void
     */
    public function testTestMode()
    {
        $testMode = $this->faker->bool();

        $this->assertSame($this->gateway, $this->gateway->setTestMode($testMode));
        $this->assertSame($testMode, $this->gateway->getTestMode());
    }

    /**
     * @return void
     */
    public function testMinChargebackProbability()
    {
        $minChargebackProbability = $this->faker->chargebackProbability();

        $this->assertSame($this->gateway, $this->gateway->setMinChargebackProbability($minChargebackProbability));
        $this->assertSame($minChargebackProbability, $this->gateway->getMinChargebackProbability());
    }

    /**
     * @return void
     */
    public function testAuthorize()
    {
        $currency = $this->faker->currency();
        $amount = $this->faker->monetaryAmount($currency);
        $customerId = $this->faker->customerId();
        $card = $this->faker->card();

        $request = $this->gateway->authorize(
            array(
                'amount' => $amount,
                'currency' => $currency,
                'card' => $card,
                'customerId' => $customerId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\AuthorizeRequest', $request);
        $this->assertSame($amount, $request->getAmount());
        $this->assertSame($currency, $request->getCurrency());
        $this->assertSameCard($card, $request->getCard());
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testCapture()
    {
        $transactionId = $this->faker->transactionId();

        $request = $this->gateway->capture(
            array(
                'transactionId' => $transactionId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\CaptureRequest', $request);
        $this->assertSame($transactionId, $request->getTransactionId());
    }

    /**
     * @return void
     */
    public function testPurchase()
    {
        $currency = $this->faker->currency();
        $amount = $this->faker->monetaryAmount($currency);
        $customerId = $this->faker->customerId();
        $card = $this->faker->card();

        $request = $this->gateway->purchase(
            array(
                'amount' => $amount,
                'currency' => $currency,
                'card' => $card,
                'customerId' => $customerId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\PurchaseRequest', $request);
        $this->assertSame($amount, $request->getAmount());
        $this->assertSame($currency, $request->getCurrency());
        $this->assertSameCard($card, $request->getCard());
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testVoid()
    {
        $transactionId = $this->faker->transactionId();

        $request = $this->gateway->void(
            array(
                'transactionId' => $transactionId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\VoidRequest', $request);
        $this->assertSame($transactionId, $request->getTransactionId());
    }

    /**
     * @return void
     */
    public function testRefund()
    {
        $currency = $this->faker->currency();
        $refundAmount = $this->faker->monetaryAmount($currency);
        $transactionAmount = $this->faker->monetaryAmount($currency);
        // make transactionAmount >= refundAmount
        if ($transactionAmount < $refundAmount) {
            $temp = $transactionAmount;
            $transactionAmount = $refundAmount;
            $refundAmount = $temp;
            unset($temp);
        }

        $transactionId = $this->faker->transactionId();
        $transactionReference = $this->faker->transactionReference();
        $reason = $this->faker->refundReason();

        $request = $this->gateway->refund(
            array(
                'amount' => $refundAmount,
                'currency' => $currency,
                'transactionId' => $transactionId,
                'transactionReference' => $transactionReference,
                'reason' => $reason
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\RefundRequest', $request);
        $this->assertSame($refundAmount, $request->getAmount());
        $this->assertSame($currency, $request->getCurrency());
        $this->assertSame($transactionId, $request->getTransactionId());
        $this->assertSame($transactionReference, $request->getTransactionReference());
        $this->assertSame($reason, $request->getReason());
    }

    /**
     * @return void
     */
    public function testCreatePaymentMethod()
    {
        $card = $this->faker->card();
        $customerId = $this->faker->customerId();

        $request = $this->gateway->createPaymentMethod(
            array(
                'card' => $card,
                'customerId' => $customerId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreatePaymentMethodRequest', $request);
        $this->assertSameCard($card, $request->getCard());
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testUpdatePaymentMethod()
    {
        $card = $this->faker->card();
        $customerId = $this->faker->customerId();

        $request = $this->gateway->updatePaymentMethod(
            array(
                'card' => $card,
                'customerId' => $customerId
            )
        );

        // update uses create's request since they're the same
        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreatePaymentMethodRequest', $request);
        $this->assertSameCard($card, $request->getCard());
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testCreateCustomer()
    {
        $currency = $this->faker->currency();
        $name = $this->faker->name();
        $email = $this->faker->email();
        $customerId = $this->faker->customerId();

        $request = $this->gateway->createCustomer(
            array(
                'name' => $name,
                'email' => $email,
                'customerId' => $customerId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreateCustomerRequest', $request);
        $this->assertSame($name, $request->getName());
        $this->assertSame($email, $request->getEmail());
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testUpdateCustomer()
    {
        $currency = $this->faker->currency();
        $name = $this->faker->name();
        $email = $this->faker->email();
        $customerId = $this->faker->customerId();

        $request = $this->gateway->updateCustomer(
            array(
                'name' => $name,
                'email' => $email,
                'customerId' => $customerId
            )
        );

        // update uses create's request since they're the same
        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreateCustomerRequest', $request);
        $this->assertSame($name, $request->getName());
        $this->assertSame($email, $request->getEmail());
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testCreatePlan()
    {
        $planId = $this->faker->planId();
        $interval = $this->faker->billingInterval();
        $intervalCount = $this->faker->billingIntervalCount();
        $prices = $this->faker->pricesAsArray();
        $statementDescriptor = $this->faker->statementDescriptor();
        $taxClassification = $this->faker->taxClassification();

        $request = $this->gateway->createPlan(
            array(
                'planId' => $planId,
                'interval' => $interval,
                'intervalCount' => $intervalCount,
                'prices' => $prices,
                'statementDescriptor' => $statementDescriptor,
                'taxClassification' => $taxClassification
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreatePlanRequest', $request);
        $this->assertSame($planId, $request->getPlanId());
        $this->assertSame($interval, $request->getInterval());
        $this->assertSame($intervalCount, $request->getIntervalCount());
        $this->assertEquals((new PriceBag($prices)), $request->getPrices());
        $this->assertSame($statementDescriptor, $request->getStatementDescriptor());
        $this->assertSame($taxClassification, $request->getTaxClassification());
    }

    /**
     * @return void
     */
    public function testUpdatePlan()
    {
        $planId = $this->faker->planId();
        $interval = $this->faker->billingInterval();
        $intervalCount = $this->faker->billingIntervalCount();
        $prices = $this->faker->pricesAsArray();
        $statementDescriptor = $this->faker->statementDescriptor();
        $taxClassification = $this->faker->taxClassification();

        $request = $this->gateway->updatePlan(
            array(
                'planId' => $planId,
                'interval' => $interval,
                'intervalCount' => $intervalCount,
                'prices' => $prices,
                'statementDescriptor' => $statementDescriptor,
                'taxClassification' => $taxClassification
            )
        );

        // update uses create's request since they're the same
        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreatePlanRequest', $request);
        $this->assertSame($planId, $request->getPlanId());
        $this->assertSame($interval, $request->getInterval());
        $this->assertSame($intervalCount, $request->getIntervalCount());
        $this->assertEquals((new PriceBag($prices)), $request->getPrices());
        $this->assertSame($statementDescriptor, $request->getStatementDescriptor());
        $this->assertSame($taxClassification, $request->getTaxClassification());
    }

    /**
     * @return void
     */
    public function testCreateProduct()
    {
        $productId = $this->faker->productId();
        $planId = $this->faker->planId();
        $prices = $this->faker->pricesAsArray();
        $statementDescriptor = $this->faker->statementDescriptor();
        $taxClassification = $this->faker->taxClassification();
        $duplicateBehavior = $this->faker->duplicateBehavior();

        $request = $this->gateway->createProduct(
            array(
                'productId' => $productId,
                'planId' => $planId,
                'duplicateBehavior' => $duplicateBehavior,
                'statementDescriptor' => $statementDescriptor,
                'taxClassification' => $taxClassification,
                'prices' => $prices,
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreateProductRequest', $request);
        $this->assertSame($planId, $request->getPlanId());
        $this->assertSame($productId, $request->getProductId());
        $this->assertSame($duplicateBehavior, $request->getDuplicateBehavior());
        $this->assertEquals((new PriceBag($prices)), $request->getPrices());
        $this->assertSame($statementDescriptor, $request->getStatementDescriptor());
        $this->assertSame($taxClassification, $request->getTaxClassification());
    }

    /**
     * @return void
     */
    public function testUpdateProduct()
    {
        $productId = $this->faker->productId();
        $planId = $this->faker->planId();
        $prices = $this->faker->pricesAsArray();
        $statementDescriptor = $this->faker->statementDescriptor();
        $taxClassification = $this->faker->taxClassification();
        $duplicateBehavior = $this->faker->duplicateBehavior();

        $request = $this->gateway->updateProduct(
            array(
                'productId' => $productId,
                'planId' => $planId,
                'duplicateBehavior' => $duplicateBehavior,
                'statementDescriptor' => $statementDescriptor,
                'taxClassification' => $taxClassification,
                'prices' => $prices,
            )
        );

        // update uses create's request since they're the same
        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreateProductRequest', $request);
        $this->assertSame($planId, $request->getPlanId());
        $this->assertSame($productId, $request->getProductId());
        $this->assertSame($duplicateBehavior, $request->getDuplicateBehavior());
        $this->assertEquals((new PriceBag($prices)), $request->getPrices());
        $this->assertSame($statementDescriptor, $request->getStatementDescriptor());
        $this->assertSame($taxClassification, $request->getTaxClassification());
    }

    /**
     * @return void
     */
    public function testCreateSubscription()
    {
        $subscriptionId = $this->faker->subscriptionId();
        $planId = $this->faker->planId();
        $customerId = $this->faker->customerId();
        $productId = $this->faker->productId();
        $currency = $this->faker->currency();
        $statementDescriptor = $this->faker->statementDescriptor();
        $ip = $this->faker->ipAddress();
        $startTime = $this->faker->timestamp();
        $card = $this->faker->card();
        $paymentMethodId = $this->faker->paymentMethodId();

        $request = $this->gateway->createSubscription(
            array(
                'planId' => $planId,
                'subscriptionId' => $subscriptionId,
                'productId' => $productId,
                'customerId' => $customerId,
                'statementDescriptor' => $statementDescriptor,
                'currency' => $currency,
                'ip' => $ip,
                'startTime' => $startTime,
                'card' => $card,
                'paymentMethodId' => $paymentMethodId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreateSubscriptionRequest', $request);
        $this->assertSame($planId, $request->getPlanId());
        $this->assertSame($productId, $request->getProductId());
        $this->assertSame($statementDescriptor, $request->getStatementDescriptor());
        $this->assertSame($subscriptionId, $request->getSubscriptionId());
        $this->assertSame($customerId, $request->getCustomerId());
        $this->assertSame($currency, $request->getCurrency());
        $this->assertSame($ip, $request->getIp());
        $this->assertSame($startTime, $request->getStartTime());
        $this->assertSame($paymentMethodId, $request->getPaymentMethodId());
        $this->assertSameCard($card, $request->getCard());
    }

    /**
     * @return void
     */
    public function testUpdateSubscription()
    {
        $subscriptionId = $this->faker->subscriptionId();
        $planId = $this->faker->planId();
        $customerId = $this->faker->customerId();
        $productId = $this->faker->productId();
        $currency = $this->faker->currency();
        $statementDescriptor = $this->faker->statementDescriptor();
        $ip = $this->faker->ipAddress();
        $startTime = $this->faker->timestamp();
        $card = $this->faker->card();
        $paymentMethodId = $this->faker->paymentMethodId();

        $request = $this->gateway->updateSubscription(
            array(
                'planId' => $planId,
                'subscriptionId' => $subscriptionId,
                'productId' => $productId,
                'customerId' => $customerId,
                'statementDescriptor' => $statementDescriptor,
                'currency' => $currency,
                'ip' => $ip,
                'startTime' => $startTime,
                'card' => $card,
                'paymentMethodId' => $paymentMethodId
            )
        );

        // update uses update's request since they're the same
        $this->assertInstanceOf('Omnipay\Vindicia\Message\CreateSubscriptionRequest', $request);
        $this->assertSame($planId, $request->getPlanId());
        $this->assertSame($productId, $request->getProductId());
        $this->assertSame($statementDescriptor, $request->getStatementDescriptor());
        $this->assertSame($subscriptionId, $request->getSubscriptionId());
        $this->assertSame($customerId, $request->getCustomerId());
        $this->assertSame($currency, $request->getCurrency());
        $this->assertSame($ip, $request->getIp());
        $this->assertSame($startTime, $request->getStartTime());
        $this->assertSame($paymentMethodId, $request->getPaymentMethodId());
        $this->assertSameCard($card, $request->getCard());
    }

    /**
     * @return void
     */
    public function testCancelSubscription()
    {
        $subscriptionId = $this->faker->subscriptionId();
        $subscriptionReference = $this->faker->subscriptionReference();

        $request = $this->gateway->cancelSubscription(
            array(
                'subscriptionId' => $subscriptionId,
                'subscriptionReference' => $subscriptionReference,
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\CancelSubscriptionRequest', $request);
        $this->assertSame($subscriptionId, $request->getSubscriptionId());
        $this->assertSame($subscriptionReference, $request->getSubscriptionReference());
    }

    /**
     * @return void
     */
    public function testCancelSubscriptions()
    {
        $numSubscriptions = $this->faker->intBetween(0, 3);
        $subscriptionIds = array();
        for ($i = 0; $i < $numSubscriptions; $i++) {
            $subscriptionIds[] = $this->faker->subscriptionId();
        }
        if (empty($subscriptionIds)) {
            $subscriptionIds = null;
        }

        $customerId = $this->faker->customerId();

        $request = $this->gateway->cancelSubscriptions(
            array(
                'customerId' => $customerId,
                'subscriptionIds' => $subscriptionIds
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\CancelSubscriptionsRequest', $request);
        $this->assertSame($subscriptionIds, $request->getSubscriptionIds());
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testFetchTransaction()
    {
        $transactionId = $this->faker->transactionId();

        $request = $this->gateway->fetchTransaction(
            array(
                'transactionId' => $transactionId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchTransactionRequest', $request);
        $this->assertSame($transactionId, $request->getTransactionId());
    }

    /**
     * @return void
     */
    public function testFetchTransactions()
    {
        $customerId = $this->faker->customerId();

        $request = $this->gateway->fetchTransactions(
            array(
                'customerId' => $customerId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchTransactionsRequest', $request);
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testFetchProduct()
    {
        $productId = $this->faker->productId();

        $request = $this->gateway->fetchProduct(
            array(
                'productId' => $productId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchProductRequest', $request);
        $this->assertSame($productId, $request->getProductId());
    }

    /**
     * @return void
     */
    public function testFetchSubscription()
    {
        $subscriptionId = $this->faker->subscriptionId();

        $request = $this->gateway->fetchSubscription(
            array(
                'subscriptionId' => $subscriptionId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchSubscriptionRequest', $request);
        $this->assertSame($subscriptionId, $request->getSubscriptionId());
    }

    /**
     * @return void
     */
    public function testFetchSubscriptions()
    {
        $customerId = $this->faker->customerId();

        $request = $this->gateway->fetchSubscriptions(
            array(
                'customerId' => $customerId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchSubscriptionsRequest', $request);
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testFetchCustomer()
    {
        $customerId = $this->faker->customerId();

        $request = $this->gateway->fetchCustomer(
            array(
                'customerId' => $customerId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchCustomerRequest', $request);
        $this->assertSame($customerId, $request->getCustomerId());
    }

    /**
     * @return void
     */
    public function testFetchPaymentMethod()
    {
        $paymentMethodId = $this->faker->paymentMethodId();

        $request = $this->gateway->fetchPaymentMethod(
            array(
                'paymentMethodId' => $paymentMethodId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchPaymentMethodRequest', $request);
        $this->assertSame($paymentMethodId, $request->getPaymentMethodId());
    }

    /**
     * @return void
     */
    public function testFetchPaymentMethods()
    {
        $customerId = $this->faker->customerId();
        $customerReference = $this->faker->customerReference();

        $request = $this->gateway->fetchPaymentMethods(
            array(
                'customerId' => $customerId,
                'customerReference' => $customerReference
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchPaymentMethodsRequest', $request);
        $this->assertSame($customerId, $request->getCustomerId());
        $this->assertSame($customerReference, $request->getCustomerReference());
    }

    /**
     * @return void
     */
    public function testFetchPlan()
    {
        $planId = $this->faker->planId();

        $request = $this->gateway->fetchPlan(
            array(
                'planId' => $planId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchPlanRequest', $request);
        $this->assertSame($planId, $request->getPlanId());
    }

    /**
     * @return void
     */
    public function testFetchRefunds()
    {
        $transactionId = $this->faker->transactionId();

        $request = $this->gateway->fetchRefunds(
            array(
                'transactionId' => $transactionId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchRefundsRequest', $request);
        $this->assertSame($transactionId, $request->getTransactionId());
    }

    /**
     * @return void
     */
    public function testFetchChargebacks()
    {
        $transactionId = $this->faker->transactionId();

        $request = $this->gateway->fetchChargebacks(
            array(
                'transactionId' => $transactionId
            )
        );

        $this->assertInstanceOf('Omnipay\Vindicia\Message\FetchChargebacksRequest', $request);
        $this->assertSame($transactionId, $request->getTransactionId());
    }

    /**
     * @return void
     */
    public function testCalculateSalesTax()
    {
        $currency = $this->faker->currency();
        $amount = $this->faker->monetaryAmount($currency);
        $card = $this->faker->card();
        $taxClassification = $this->faker->taxClassification();

        $request = $this->gateway->calculateSalesTax(
            array(
                'amount' => $amount,
                'currency' => $currency,
                'card' => $card,
                'taxClassification' => $taxClassification
            )
        );

        $this->assertSame($amount, $request->getAmount());
        $this->assertSame($card['country'], $request->getCard()->getCountry());
        $this->assertSame($currency, $request->getCurrency());
        $this->assertSame($taxClassification, $request->getTaxClassification());
    }

    /**
     * @return void
     */
    public function testDefaultMinChargebackProbability()
    {
        $currency = $this->faker->currency();
        $amount = $this->faker->monetaryAmount($currency);
        $customerId = $this->faker->customerId();
        $card = $this->faker->card();

        // if there's no min chargeback probability set, request should take its default

        $this->assertNull($this->gateway->getMinChargebackProbability());

        $request = $this->gateway->authorize(
            array(
                'amount' => $amount,
                'currency' => $currency,
                'card' => $card,
                'customerId' => $customerId
            )
        );

        $this->assertSame(AuthorizeRequest::DEFAULT_MIN_CHARGEBACK_PROBABILITY, $request->getMinChargebackProbability());

        // if a gateway default is set, the request should take that

        $minChargebackProbability = $this->faker->chargebackProbability();
        $this->gateway->setMinChargebackProbability($minChargebackProbability);

        $request = $this->gateway->authorize(
            array(
                'amount' => $amount,
                'currency' => $currency,
                'card' => $card,
                'customerId' => $customerId
            )
        );

        $this->assertSame($minChargebackProbability, $request->getMinChargebackProbability());

        // if a gateway default is set but the request overrides it, the request should take the override

        $overrideMinChargebackProbability = $this->faker->chargebackProbability();

        $request = $this->gateway->authorize(
            array(
                'amount' => $amount,
                'currency' => $currency,
                'card' => $card,
                'customerId' => $customerId,
                'minChargebackProbability' => $overrideMinChargebackProbability
            )
        );

        $this->assertSame($overrideMinChargebackProbability, $request->getMinChargebackProbability());
    }

    /**
     * @return void
     */
    protected function assertSameCard($card, $requestCard)
    {
        $this->assertSame($card['number'], $requestCard->getNumber());
        $this->assertSame(intval($card['expiryMonth']), $requestCard->getExpiryMonth());
        $this->assertSame(intval($card['expiryYear']), $requestCard->getExpiryYear());
    }
}


text:
<?php

namespace app\api\actions\Articles;

use Yii;
use yii\rest\Action;
use yii\base\Model;
use yii\helpers\Url;
use yii\data\ActiveDataProvider;
use yii\web\ServerErrorHttpException;
use yii\web\HttpException;
use app\models\Content;
/**
 * @author Qiang Xue <qiang.xue@gmail.com>
 * @since 2.0
 */

/**
 * Class CreateThreadAction
 * @package app\api\actions\Me
 *
 *  Creates a thread and an associated, optional post
 *  Fails only if the creation of the thread fails
 */
class CreateArticleAction extends Action
{
    public $scenario = Model::SCENARIO_DEFAULT;
    public $viewAction = 'view';

    public function run()
    {
        if ($this->checkAccess)
        {
            call_user_func($this->checkAccess, $this->id);
        }

        $connection = Yii::$app->db;
        $transaction = $connection->beginTransaction();
        try {
            $content = new Content([
                'scenario' => $this->scenario,
            ]);
            $content->load(Yii::$app->getRequest()->getBodyParams(), '');
            if (!$content->save()){
                if ($content->hasErrors())
                {
                    $transaction->rollBack();
                    return $content;
                }
                else
                {
                    throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
                }
            }

            $article = new $this->modelClass([
                'scenario' => $this->scenario,
            ]);
            $article->id = $content->id;
            $article->load(Yii::$app->getRequest()->getBodyParams(), '');
            if (!$article->save()){
                if ($article->hasErrors())
                {
                    $transaction->rollBack();
                    return $article;
                }
                else
                {
                    throw new ServerErrorHttpException('Failed to create the object for unknown reason.');
                }
            }
            $transaction->commit();
            $response = Yii::$app->getResponse();
            $response->setStatusCode(201);
            $id = implode(',', array_values($article->getPrimaryKey(true)));
            $response->getHeaders()->set('Location', Url::toRoute([$this->viewAction, 'id' => $id], true));
            return $content;

        } catch(\Exception $e) {
            $transaction->rollBack();
            throw $e;
        }
    }
}


text:
<!DOCTYPE html>

	<meta charset="UTF-8" />
	<meta name="viewport" content="width=device-width, initial-scale=1" />
	<link rel="stylesheet" href="style.css" />
	<title>1D Infinite Potential Wells</title>

1D Infinite Potential Well

		<canvas id="canvas" width="800" height="600"></canvas>

Legend: Real Imaginary Energy

Well Width

		<input id="well_width_slider" type="range" min="0.3" max="1.0" value="1.0" step="0.01" onchange="handle_slider();">
		<input id="show_psi" type="checkbox" value="runClock"> Time Dependent

		<input id="excite_button" type="button" value="Excite" onclick="handle_excite();">
		<input id="deexcite_button" type="button" value="De-excite" onclick="handle_deexcite();">

0 nm

0 Hz

0 eV


text:
function roc_scoreStation = plotROCstations(GHCND_clustered, cutofflength, C, lag_range, lagsToPlot, ...
	fig_folder, summerDays, yrs, summer_doy, cone_ratio, predictandName)

% Station by station
rng('default')
clear cache_input
% also calculate for each station
stationAnom = bsxfun(@minus, GHCND_clustered.anomTotal, nanmean(GHCND_clustered.anomTotal(:, summerDays), 2));
cache_input.data = stationAnom;
cache_input.lag_range = lag_range;
cache_input.predictand = predictandName;
ROCstationHash = DataHash(cache_input);
matname =['/n/huybers_lab/common/ghcnd/analysis/composites/cache/ROC_' ROCstationHash '.mat'];
if exist(matname, 'file')
	load(matname)
else
	for ct = 1:size(stationAnom, 1)
		disp(['' num2str(ct) ''])
		[startDateStation{ct}, endDateStation{ct}, totalTempStation{ct}, alldaysStation{ct}] = ...
			findHotDays(GHCND_clustered, cutofflength, stationAnom(ct, :), summerDays, ...
			yrs, summer_doy);
	end

	roc_scoreStation = NaN(length(lag_range), size(stationAnom, 1));
	predictand = eval(cache_input.predictand);
	for ct = 1:size(stationAnom, 1)
		disp(['' num2str(ct) ''])
		[roc_scoreStation(:, ct)] = ...
			calcROC(GHCND_clustered, C, cone_ratio, lag_range, predictand{ct}, ...
				summer_doy, 0, fig_folder, GHCND_clustered.id(ct, :));

	end
	timestamp = datestr(now);
	save(matname, 'roc_scoreStation', 'timestamp');
end

cmap = varycolor(5);
cmap = [0.3*[1 1 1];cmap];
for jj = 1:length(lagsToPlot)
	idx = find(lag_range == lagsToPlot(jj));
	clf
	m_proj('miller', 'lat', [25 50], 'lon', [-105 -60]);
	hold on
	m_coast('patch', 0.9*[1 1 1],'edgecolor','none');
	m_grid('linestyle','none','fontsize',24,'tickdir','in');
	[sx, sy] = m_ll2xy(GHCND_clustered.location(:, 1), GHCND_clustered.location(:, 2));
	colormap(cmap)
	caxis([0.45 0.75])
	h = colorbar;
	set(h,'fontsize',24)
	hold on
	scatter(sx, sy, 150, roc_scoreStation(idx,:), '.','linewidth',2)
	title(['Lead time: ' num2str(lagsToPlot(jj)) ' days'])
	set(gca,'fontsize',14)
	orient landscape
	set(gcf,'Renderer','zbuffer')
	fig_name = ['ROCScores_StationMaps_lag' num2str(lagsToPlot(jj)) '_' predictandName '.ps'];
	print('-dpsc',[fig_folder '/' fig_name]);
end

% Make histograms
xi = linspace(0.3,0.8,100);
bw = 0.02;
clf
hold on
colors = flipud(lbmap(length(lagsToPlot),'brownblue'));
for jj = 1:length(lagsToPlot)
	idx = find(lag_range == lagsToPlot(jj));
	fi = ksdensity(roc_scoreStation(idx,:),xi,'bandwidth',bw);
	h(jj) = plot(xi,fi,'color',colors(jj,:),'linewidth',4);
	legend_text{jj} = [num2str(lagsToPlot(jj)) ' days'];
end
grid on
hl = legend(h,strtrim(cellstr(legend_text)),'location','northwest');
set(hl,'fontsize',20)
xlabel('ROC score')
ylabel('Probability density')
xlim([min(xi) max(xi)])
figname = ['ROCScores_StationDensity_' predictandName '.ps'];

orient landscape
print('-dpsc',[fig_folder '/' figname])


text:
layout: project
lab: OK Lab Jena
title: Linked Open Haushalt

links:
- url: http://www.offenes-jena.com/Apps/OffenerHaushalt
  name: Offener Haushalt
- url: https://github.com/OffenesJena/OffenerHaushalt
  name: GitHub Repository

collaborators:
- name: Achim Friedland
- name: Martin Berger (Stadtverwaltung Jena)
---

Der offene Haushalt mit seiner wohlbekannten TreeMap-Visualisierung ist natürlich der interessanteste Datensatz jeder offenen Stadt.
Wir gehen einen Schritt weiter und setzen den Haushalt direkt mit vielen anderen Datensätzen in Beziehung. So kann wird der Offene Haushalt
nicht nur auf einer Landkarte dargestellt, sondern auch im jeweiligen Kontext anderer Datensätze wie z.B. der Übersicht über alle KiTas und Schulen.


text:
using System;

namespace CoinAPI.WebSocket.V1.DataModels
{
    public struct Volume
    {
        public DateTime time_coinapi { get; set; }
        public string period_id { get; set; }
        public SymbolVolume[] volume_by_symbol { get; set; }
    }
    public struct SymbolVolume
    {
        public string symbol_id { get; set; }
        public string asset_id_base { get; set; }
        public string asset_id_quote { get; set; }
        public decimal volume_base { get; set; }
        public decimal volume_quote { get; set; }
    }
}


text:
class Book < ActiveRecord::Base
  has_many :book_authors, dependent: :destroy
  has_many :authors, through: :book_authors
  belongs_to :category

  validates :title, presence: true
  validates :price, presence: true

  # #author_names returns a string with author full_names devided by ", "
  def author_names
    self.authors.inject('') do |str, author|
      str << ', ' unless str.empty?
      str << author.full_name
    end
  end
end


text:
package com.kaleksandrov.smp.ui.view;

import android.content.Context;
import android.graphics.Rect;
import android.support.v7.widget.RecyclerView;
import android.view.View;

import java.lang.ref.WeakReference;

/**
 * Created by kaleksandrov on 5/14/15.
 */
public class GeneralPaddingItemDecoration extends RecyclerView.ItemDecoration {

    private static final int PADDING_DP = 8;
    private final WeakReference<Context> mContextRef;

    public GeneralPaddingItemDecoration(Context context) {
        mContextRef = new WeakReference<>(context);
    }

    @Override
    public void getItemOffsets(Rect outRect, View view, RecyclerView parent, RecyclerView.State state) {
        super.getItemOffsets(outRect, view, parent, state);

        Context context = mContextRef.get();
        if (context != null) {
            //TODO [kaleksandrov] Move this to utility method
            float px = PADDING_DP * context.getResources().getDisplayMetrics().density;
            outRect.left += px;
            outRect.right += px;
        }
    }

}


text:
#ifndef MCOMP_X86_H
#define MCOMP_X86_H

#if HAVE_SSE3
#if !CONFIG_RUNTIME_CPU_DETECT

#undef  vp8_search_full_search
#define vp8_search_full_search vp8_full_search_sadx3

#undef  vp8_search_diamond_search
#define vp8_search_diamond_search vp8_diamond_search_sadx4

#endif
#endif

#if HAVE_SSE4_1
#if !CONFIG_RUNTIME_CPU_DETECT

#undef  vp8_search_full_search
#define vp8_search_full_search vp8_full_search_sadx8

#endif
#endif

#endif


text:
package com.alipay.api.response;

import com.alipay.api.internal.mapping.ApiField;
import com.alipay.api.domain.AlipayUserDetail;

import com.alipay.api.AlipayResponse;

/**
 * ALIPAY API: alipay.user.get response.
 *
 * @author auto create
 * @since 1.0, 2018-02-28 16:34:11
 */
public class AlipayUserGetResponse extends AlipayResponse {

	private static final long serialVersionUID = 6382837717145276791L;

	/**
	 * 支付宝用户信息
	 */
	@ApiField("alipay_user_detail")
	private AlipayUserDetail alipayUserDetail;

	public void setAlipayUserDetail(AlipayUserDetail alipayUserDetail) {
		this.alipayUserDetail = alipayUserDetail;
	}
	public AlipayUserDetail getAlipayUserDetail( ) {
		return this.alipayUserDetail;
	}

}


text:
from satchmo.configuration import *
from django.utils.translation import ugettext_lazy as _

# this is so that the translation utility will pick up the string
gettext = lambda s: s
_strings = (gettext('CreditCard'), gettext('Credit Card'))

PAYMENT_MODULES = config_get('PAYMENT', 'MODULES')
PAYMENT_MODULES.add_choice(('PAYMENT_AUTHORIZENET', 'Authorize.net'))

PAYMENT_GROUP = ConfigurationGroup('PAYMENT_AUTHORIZENET',
    _('Authorize.net Payment Settings'),
    requires=PAYMENT_MODULES,
    ordering=101)

config_register_list(

    StringValue(PAYMENT_GROUP,
        'CONNECTION',
        description=_("Submit to URL"),
        help_text=_("""This is the address to submit live transactions."""),
        default='https://secure.authorize.net/gateway/transact.dll'),

    StringValue(PAYMENT_GROUP,
        'CONNECTION_TEST',
        description=_("Submit to Test URL"),
        help_text=("""A Quick note on the urls.<br/>
If you are posting to https://test.authorize.net/gateway/transact.dll,
and you are not using an account whose API login ID starts with
"cpdev" or "cnpdev", you will get an Error 13 message.
Make sure you are posting to https://certification.authorize.net/gateway/transact.dll
for test transactions if you do not have a cpdev or cnpdev.
"""),
        default='https://test.authorize.net/gateway/transact.dll'),

    BooleanValue(PAYMENT_GROUP,
        'SSL',
        description=_("Use SSL for the checkout pages?"),
        default=False),

    BooleanValue(PAYMENT_GROUP,
        'LIVE',
        description=_("Accept real payments"),
        help_text=_("False if you want to submit to the test urls."),
        default=False),

    BooleanValue(PAYMENT_GROUP,
        'SIMULATE',
        description=_("Force a test post?"),
        help_text=_("True if you want to submit to the live url using a test flag, which won't be accepted."),
        default=False),

    ModuleValue(PAYMENT_GROUP,
        'MODULE',
        description=_('Implementation module'),
        hidden=True,
        default = 'satchmo.payment.modules.authorizenet'),

    StringValue(PAYMENT_GROUP,
        'KEY',
        description=_("Module key"),
        hidden=True,
        default = 'AUTHORIZENET'),

    StringValue(PAYMENT_GROUP,
        'LABEL',
        description=_('English name for this group on the checkout screens'),
        default = 'Credit Cards',
        help_text = _('This will be passed to the translation utility')),

    StringValue(PAYMENT_GROUP,
        'URL_BASE',
        description=_('The url base used for constructing urlpatterns which will use this module'),
        default = r'^credit/'),

    MultipleStringValue(PAYMENT_GROUP,
        'CREDITCHOICES',
        description=_('Available credit cards'),
        choices = (
            (('American Express', 'American Express')),
            (('Visa','Visa')),
            (('Mastercard','Mastercard')),
            (('Discover','Discover'))),
        default = ('Visa', 'Mastercard', 'Discover')),

    StringValue(PAYMENT_GROUP,
        'LOGIN',
        description=_('Your authorize.net transaction login'),
        default=""),

    StringValue(PAYMENT_GROUP,
        'TRANKEY',
        description=_('Your authorize.net transaction key'),
        default=""),

    BooleanValue(PAYMENT_GROUP,
        'CAPTURE',
        description=_('Capture Payment?'),
        default=True,
        help_text=_('IMPORTANT: If false, you will need to manually go to your authorize.net merchant account and capture payments.  Setting this to false means you are authorizing the card only, not capturing payment.')),

    BooleanValue(PAYMENT_GROUP,
        'EXTRA_LOGGING',
        description=_("Verbose logs"),
        help_text=_("Add extensive logs during post."),
        default=False)

)

ARB_ENABLED = config_register(
    BooleanValue(PAYMENT_GROUP,
        'ARB',
        description=_('Enable ARB?'),
        default=False,
        help_text=_('Enable ARB processing for setting up subscriptions.  You must have this enabled in your Authorize account for it to work.')))

config_register(
    StringValue(PAYMENT_GROUP,
        'ARB_CONNECTION',
        description=_("Submit to URL (ARB)"),
        help_text=_("""This is the address to submit live transactions for ARB."""),
        requires=ARB_ENABLED,
        default='https://api.authorize.net/xml/v1/request.api'))

config_register(
    StringValue(PAYMENT_GROUP,
        'ARB_CONNECTION_TEST',
        description=_("Submit to Test URL (ARB)"),
        help_text=_("""This is the address to submit test transactions for ARB."""),
        requires=ARB_ENABLED,
        default='https://apitest.authorize.net/xml/v1/request.api'))


text:
import React from "react";
import ReactDOM from "react-dom";
import Content from "./Content";
import { shallow } from "enzyme";

it("renders without crashing", () => {
  const div = document.createElement("div");
  ReactDOM.render(<Content content={"foo"} />, div);
});

it("renders a text field with the specified value", () => {
  const div = document.createElement("div");
  const subject = shallow(<Content content={"foo"} />);

  expect(subject.text()).toBe("foo");
});


text:
from rest_framework import viewsets
from rest_framework.decorators import api_view
from rest_framework.response import Response
from rest_framework.reverse import reverse
from vaf_Api.models import Franchise, Manager, Equipment, Player, Location, Team, Game
from vaf_Api.serializers import FranchiseSerializer, ManagerSerializer, EquipmentSerializer, PlayerSerializer, LocationSerializer, TeamSerializer, GameSerializer

# Create your views here.
class FranchiseList(viewsets.ModelViewSet):
  queryset =Franchise.objects.all()
  serializer_class = FranchiseSerializer
  # permission_classes = (IsOwnerOrReadOnly,) will need to create this class later
  # video on Django,Rest,Ang on permissions and file and objects

class ManagerList(viewsets.ModelViewSet):
  queryset =Manager.objects.all()
  serializer_class = ManagerSerializer

class EquipmentList(viewsets.ModelViewSet):
  queryset =Equipment.objects.all()
  serializer_class = EquipmentSerializer

class PlayerList(viewsets.ModelViewSet):
  queryset =Player.objects.all()
  serializer_class = PlayerSerializer

class LocationList(viewsets.ModelViewSet):
  queryset =Location.objects.all()
  serializer_class = LocationSerializer

class TeamList(viewsets.ModelViewSet):
  queryset =Team.objects.all()
  serializer_class = TeamSerializer

class GameList(viewsets.ModelViewSet):
  queryset =Game.objects.all()
  serializer_class = GameSerializer


text:
<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.pusherman.networkinfo" >
    <uses-permission android:name="android.permission.INTERNET"/>
  	<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
  	<uses-permission android:name="android.permission.ACCESS_WIFI_STATE"/>
</manifest>


text:
#ifndef _PEI_SEC_PLATFORM_INFORMATION_PPI_H
#define _PEI_SEC_PLATFORM_INFORMATION_PPI_H

#define EFI_SEC_PLATFORM_INFORMATION_GUID \
  { \
    0x6f8c2b35, 0xfef4, 0x448d, {0x82, 0x56, 0xe1, 0x1b, 0x19, 0xd6, 0x10, 0x77} \
  }

EFI_FORWARD_DECLARATION (EFI_SEC_PLATFORM_INFORMATION_PPI);

extern EFI_GUID gEfiSecPlatformInformationPpiGuid;

typedef struct {
  UINTN HealthFlags;
} SEC_PLATFORM_INFORMATION_RECORD;

typedef struct {
  UINTN BootPhase;      // entry r20 value
  UINTN UniqueId;       // PAL arbitration ID
  UINTN HealthStat;     // Health Status
  UINTN PALRetAddress;  // return address to PAL
} IPF_HANDOFF_STATUS;

typedef
EFI_STATUS
(EFIAPI *SEC_PLATFORM_INFORMATION) (
  IN EFI_PEI_SERVICES                    **PeiServices,
  IN OUT UINT64                          *StructureSize,
  IN OUT SEC_PLATFORM_INFORMATION_RECORD * PlatformInformationRecord
  );

struct _EFI_SEC_PLATFORM_INFORMATION_PPI {
  SEC_PLATFORM_INFORMATION  PlatformInformation;
};

#endif


text:
"""

    BioVida-Unification Subpackage Unit Testing
    ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~

"""
import os
import sys
import unittest

# Allow access to modules
sys.path.insert(0, os.path.abspath("."))
sys.path.insert(0, os.path.abspath("../"))

from biovida import unification

class UnificationTests(unittest.TestCase):
    """

    Unit Tests for the Unification Subpackage.

    """

    def test(self):
        self.assertEqual(1, 1)

unittest.main()


text:
<beans xmlns="http://www.springframework.org/schema/beans"
       xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
       xmlns:util="http://www.springframework.org/schema/util"
       xmlns:p="http://www.springframework.org/schema/p"
       xmlns:tx="http://www.springframework.org/schema/tx"
       xsi:schemaLocation="
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-2.5.xsd
http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx-2.5.xsd
http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

    <bean name="propertyConfigurer" class="org.springframework.context.support.PropertySourcesPlaceholderConfigurer">
        <property name="locations">
            <list>
                <value>classpath:progressive.db.properties</value>
            </list>
        </property>
        <property name="ignoreResourceNotFound" value="true"/>
    </bean>

    <!-- jdbc data source -->
    <bean id="dataSource" class="org.apache.tomcat.jdbc.pool.DataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driver}"/>
        <property name="url" value="${jdbc.url}"/>
        <property name="username" value="${jdbc.username}"/>
        <property name="password" value="${jdbc.password}"/>
        <property name="initialSize" value="2"/>
    </bean>

    <!-- Spring transaction management -->
    <bean id="transactionManager" class="org.springframework.jdbc.datasource.DataSourceTransactionManager">
        <property name="dataSource" ref="dataSource"/>
    </bean>

    <bean id="persistence" class="org.xillium.data.persistence.Persistence">
        <constructor-arg index="0"><ref bean="dataSource"/></constructor-arg>
        <property name="transactionManager" ref="transactionManager"/>
        <property name="intrinsics">
            <list>
                <value>/progressive.storage.xml</value>
            </list>
        </property>
    </bean>

    <tx:annotation-driven transaction-manager="transactionManager"/>

    <bean id="progressive" class="org.xillium.gear.util.Progression">
        <constructor-arg index="0"><ref bean="persistence"/></constructor-arg>
        <constructor-arg index="1"><value>-/RecallState</value></constructor-arg>
        <constructor-arg index="2"><value>-/RecallParam</value></constructor-arg>
        <constructor-arg index="3"><value>-/CommitState</value></constructor-arg>
        <constructor-arg index="4"><value>-/MarkAttempt</value></constructor-arg>
    </bean>

</beans>