text:
<!DOCTYPE html>

    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <meta name="description" content="">
    <meta name="author" content="">

    <title>OTHER WAY ROUND</title>

    <link rel="icon" href="favicon.ico" type="image/x-icon"/>
    <link rel="shortcut icon" href="favicon.ico" type="image/x-icon"/>

    <link rel="stylesheet" href="css/bootstrap.min.css" type="text/css">

    <link href='http://fonts.googleapis.com/css?family=Open+Sans:300italic,400italic,600italic,700italic,800italic,400,300,600,700,800' rel='stylesheet' type='text/css'>
    <link href='http://fonts.googleapis.com/css?family=Merriweather:400,300,300italic,400italic,700,700italic,900,900italic' rel='stylesheet' type='text/css'>
    <link rel="stylesheet" href="font-awesome/css/font-awesome.min.css" type="text/css">

    <link rel="stylesheet" href="css/animate.min.css" type="text/css">

    <link rel="stylesheet" href="css/custom.css" type="text/css">

                <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#bs-example-navbar-collapse-1">
                    Toggle navigation

                </button>

                Other Way Round

                        About

                        Destinations

                        Blog

                        Philosophy

Palestine: On the Wrong Side of the Wall

                    	Islam,
                    	Urban Exploration,
                    	Hitchhiking

 Things to do: (1) get the title text aligned at the bottom of the parent div -- right now, when the screen shrinks the title vanishes. (2) Make the title background translucent. It'll look cooler that way. (3) Create category (tag) pages. (4) Create author pages. (5) Tweak travel blog link images at bottom -- add margin around images and around image container. (6) Create all other pages. (7) Create gif of Palestinian kids running alongside us,

 "All Men Are Created Equal. And Endowed by Ahura Mazda with Guns, Drugs, and Money. BITCHES."

 Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine.

                                    This is an image of some communists. I created a div class and some spiffy CSS in order to get it here. Stalin es ochen xorosho! This also gets a second line!

 Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine.

                                    This is an image of some communists. I created a div class and some spiffy CSS in order to get it here. Stalin es ochen xorosho! This also gets a second line!

 Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine. Here's a story about Palestine.

                			 Written by Cameron Smith

                			December 05, 2014

TOP BLOG POSTS

                    See More

	                                    The Long Road From Rangoon

	                                    Hitchhiking Myanmar

	                                	Hitchhiking,
	                                	Urban Exploration

	                                    Nuclear Destruction in Japan

	                                    Ishinomaki, a town destroyed by the 2011 Tsunami

	                                	Urban Exploration,
	                                	Conflict

	                                    San Francisco's Radioactive Navy Base

	                                    A Journey to Hunter's Point Navy Facility

	                                	Urban Exploration

	                                    The Abandoned City of Varosha

	                                    A town abandoned during the Cypriot Civil War

	                                	Hitchhiking,
	                                	Conflict

	                                    Karabakh: the Country that Doesn't Exist

	                                    Hitching rides in the Caucasus Mtns

	                                	Hitchhiking,
	                                	Urban Exploration

	                                    Climbing the Great Pyramid at Night

	                                    A Risky Journey Up 4,500 years of history

	                                	Urban Exploration,
	                                	Conflict

Copyright © Other Way Round 2016


text:
package cn.jfinalbbs.link;

import cn.jfinalbbs.common.BaseController;
import cn.jfinalbbs.common.Constants;
import cn.jfinalbbs.interceptor.AdminUserInterceptor;
import com.jfinal.aop.Before;

/**
 * Created by liuyang on 15/4/26.
 */
@Before(AdminUserInterceptor.class)
public class LinkAdminController extends BaseController {

    public void index() {
        setAttr("admin_links", Link.me.findAll());
        render("index.html");
    }

    public void add() {
        String method = getRequest().getMethod();
        if(method.equalsIgnoreCase(Constants.RequestMethod.GET)) {
            render("add.html");
        } else if(method.equalsIgnoreCase(Constants.RequestMethod.POST)) {
            Integer maxDisplayIndex = Link.me.maxDisplayIndex();
            if(maxDisplayIndex == null) maxDisplayIndex = 0;
            getModel(Link.class).set("display_index", maxDisplayIndex + 1).save();
            clearCache(Constants.CacheName.LINKLIST, null);
            redirect(Constants.getBaseUrl() + "/admin/link");
        }
    }

    public void edit() {
        String method = getRequest().getMethod();
        Integer id = getParaToInt("id");
        if(method.equalsIgnoreCase(Constants.RequestMethod.GET)) {
            setAttr("link", Link.me.findById(id));
            render("edit.html");
        } else if(method.equalsIgnoreCase(Constants.RequestMethod.POST)) {
            getModel(Link.class).update();
            clearCache(Constants.CacheName.LINKLIST, null);
            redirect(Constants.getBaseUrl() + "/admin/link");
        }
    }

    public void delete() {
        Integer id = getParaToInt("id");
        if(id == null) {
            error(Constants.OP_ERROR_MESSAGE);
        } else {
            try {
                Link.me.deleteById(id);
                clearCache(Constants.CacheName.LINKLIST, null);
                success();
            } catch (Exception e) {
                e.printStackTrace();
                error(Constants.DELETE_FAILURE);
            }
        }
    }

    public void sort() {
        Integer[] ids = getParaValuesToInt("ids");
        if(ids != null && ids.length > 0) {
            for(int i = 0; i < ids.length; i++) {
                Link.me.findById(ids[i]).set("display_index", i + 1).update();
            }
            clearCache(Constants.CacheName.LINKLIST, null);
        }
        redirect(Constants.getBaseUrl() + "/admin/link");
    }
}

redpajama_set_name: RedPajamaGithub


text:
'''
The count-and-say sequence is the sequence of integers beginning as follows:
1, 11, 21, 1211, 111221, ...

1 is read off as "one 1" or 11.
11 is read off as "two 1s" or 21.
21 is read off as "one 2, then one 1" or 1211.
Given an integer n, generate the nth sequence.
'''

class Solution:
    def countAndSay(self, n):
        sequence = ['1']
        for index in range(1, n):
            sequence.append(self.generate(sequence[index-1]))
        return sequence[n-1]

    # @param {string} orig_string
    # @return {string}
    def generate(self, orig_string):
        count_string = list()
        count = 0
        for index in range(len(orig_string)):
            char = orig_string[index]
            if index > 0 and orig_string[index] != orig_string[index-1]:
                count_string.append('%s' % count)
                count_string.append(orig_string[index-1])
                count = 1
            else:
                count += 1
        count_string.append('%s' % count)
        count_string.append(orig_string[-1])

        return ''.join(count_string)

if __name__ == '__main__':
    solution = Solution()
    print solution.countAndSay(5)


text:
package org.deeplearning4j.models.sequencevectors.graph.walkers.impl;

import org.deeplearning4j.models.sequencevectors.graph.enums.NoEdgeHandling;
import org.deeplearning4j.models.sequencevectors.graph.enums.WalkDirection;
import org.deeplearning4j.models.sequencevectors.graph.primitives.Graph;
import org.deeplearning4j.models.sequencevectors.graph.vertex.AbstractVertexFactory;
import org.deeplearning4j.models.sequencevectors.graph.walkers.GraphWalker;
import org.deeplearning4j.models.sequencevectors.sequence.Sequence;
import org.deeplearning4j.models.word2vec.VocabWord;
import org.junit.Before;
import org.junit.Test;

import static org.junit.Assert.*;

/**
 * @author raver119@gmail.com
 */
public class WeightedWalkerTest {
    private static Graph<VocabWord, Integer> basicGraph;

    @Before
    public void setUp() throws Exception {
        if (basicGraph == null) {
            // we don't really care about this graph, since it's just basic graph for iteration checks
            basicGraph = new Graph<>(10, false, new AbstractVertexFactory<VocabWord>());

            for (int i = 0; i < 10; i++) {
                basicGraph.getVertex(i).setValue(new VocabWord(i, String.valueOf(i)));

                int x = i + 3;
                if (x >= 10)
                    x = 0;
                basicGraph.addEdge(i, x, 1, false);
            }

            basicGraph.addEdge(0, 4, 2, false);
            basicGraph.addEdge(0, 4, 4, false);
            basicGraph.addEdge(0, 4, 6, false);
            basicGraph.addEdge(4, 5, 8, false);
            basicGraph.addEdge(1, 3, 6, false);
            basicGraph.addEdge(9, 7, 4, false);
            basicGraph.addEdge(5, 6, 2, false);
        }
    }

    @Test
    public void testBasicIterator1() throws Exception {
        GraphWalker<VocabWord> walker = new WeightedWalker.Builder<>(basicGraph)
                        .setWalkDirection(WalkDirection.FORWARD_PREFERRED).setWalkLength(10)
                        .setNoEdgeHandling(NoEdgeHandling.RESTART_ON_DISCONNECTED).build();

        int cnt = 0;
        while (walker.hasNext()) {
            Sequence<VocabWord> sequence = walker.next();

            assertNotEquals(null, sequence);
            assertEquals(10, sequence.getElements().size());
            cnt++;
        }

        assertEquals(basicGraph.numVertices(), cnt);
    }

}


text:
<?php

/**
 *      [Discuz!] (C)2001-2099 Comsenz Inc.
 *      This is NOT a freeware, use is subject to license terms
 *
 *      $Id: cron_security_daily.php 29568 2012-04-19 03:39:25Z songlixin $
 */

if(!defined('IN_DISCUZ')) {
	exit('Access Denied');
}

$queryf = C::t('forum_forum')->fetch_all_fids();
foreach($queryf as $forum) {
	$thread = C::t('forum_thread')->fetch_by_fid_displayorder($forum['fid']);
	$lastpost = "$thread[tid]\t$thread[subject]\t$thread[lastpost]\t$thread[lastposter]";

	C::t('forum_forum')->update($forum['fid'], array('lastpost' => $lastpost));
}
?>


text:
readonly EXIT_CODE_SUCCESS=0

#
# This script should be located in coreclr/tests.
#

function print_usage {
    echo ''
    echo 'Download coredistools for GC stress testing'
    echo ''
    echo 'Command line:'
    echo ''
    echo './setup-gcstress.sh --arch=<TargetArch> --outputDir=<coredistools_lib_install_path>'
    echo ''
    echo 'Required arguments:'
    echo '  --arch=<TargetArch>        : Target arch for the build'
    echo '  --outputDir=<path>         : Directory to install libcoredistools.so'
    echo ''
}

function exit_with_error {
    local errorCode=$1
    local errorMsg=$2

    if [ ! -z "$2" ]; then
        echo $2
    fi

    exit $errorCode
}

function handle_ctrl_c {
    exit_with_error 1 'Aborted by Ctrl+C'
 }

# Register the Ctrl-C handler
trap handle_ctrl_c INT

# Argument variables
libInstallDir=

# Handle arguments
verbose=0
for i in "$@"
do
    case $i in
        -h|--help)
            exit $EXIT_CODE_SUCCESS
            ;;
        -v|--verbose)
            verbose=1
            ;;
        --arch=*)
            __BuildArch=${i#*=}
            ;;
        --outputDir=*)
            libInstallDir=${i#*=}
            ;;
        *)
            echo "Unknown switch: $i"
            print_usage
            exit $EXIT_CODE_SUCCESS
            ;;
    esac
done

if [ -z "$__BuildArch" ]; then
    echo "--arch is required."
    print_usage
    exit_with_error 1
fi

if [ -z "$libInstallDir" ]; then
    echo "--outputDir is required."
    print_usage
    exit_with_error 1
fi

if [ "$__BuildArch" == "arm64" ] || [ "$__BuildArch" == "arm" ]; then
    echo "No runtime dependencies for arm32/arm64"
    exit $EXIT_CODE_SUCCESS
fi

# This script must be located in coreclr/tests.
scriptDir="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"

dotnet=$"${scriptDir}"/../.dotnet/dotnet
packageDir="${scriptDir}"/../.packages
csprojPath="${scriptDir}"/src/Common/stress_dependencies/stress_dependencies.csproj

if [ ! -e $dotnetCmd ]; then
    exit_with_error 1 'dotnet commandline does not exist:'$dotnetCmd
fi

# make package directory
if [ ! -e $packageDir ]; then
    mkdir -p $packageDir
fi

# make output directory
if [ ! -e $libInstallDir ]; then
    mkdir -p $libInstallDir
fi

# Use uname to determine what the OS is.
OSName=$(uname -s)
case $OSName in
    Linux)
        __BuildOS=Linux
        __HostOS=Linux
        ;;

    Darwin)
        __BuildOS=OSX
        __HostOS=OSX
        ;;

    FreeBSD)
        __BuildOS=FreeBSD
        __HostOS=FreeBSD
        ;;

    OpenBSD)
        __BuildOS=OpenBSD
        __HostOS=OpenBSD
        ;;

    NetBSD)
        __BuildOS=NetBSD
        __HostOS=NetBSD
        ;;

    SunOS)
        __BuildOS=SunOS
        __HostOS=SunOS
        ;;

    *)
        echo "Unsupported OS $OSName detected, configuring as if for Linux"
        __BuildOS=Linux
        __HostOS=Linux
        ;;
esac

isPortable=0

source "${scriptDir}"/../init-distro-rid.sh
initDistroRidGlobal ${__BuildOS} x64 ${isPortable}

# Hack, replace the rid to ubuntu.14.04 which has a valid non-portable
# package.
#
# The CoreDisTools package is currently manually packaged and we only have
# 14.04 and 16.04 packages. Use the oldest package which will work on newer
# platforms.
if [[ ${__BuildOS} == "Linux" ]]; then
   __DistroRid=ubuntu.14.04
fi

# Query runtime Id
rid=${__DistroRid}

echo "Rid to be used: ${rid}"

if [ -z "$rid" ]; then
    exit_with_error 1 "Failed to query runtime Id"
fi

# Download the package
echo Downloading CoreDisTools package
bash -c -x "$dotnet restore $csprojPath --packages $packageDir"
if [ $? -ne 0 ]
then
    exit_with_error 1 "Failed to restore the package"
fi

# Get library path
libPath=`find $packageDir | grep $rid | grep -m 1 libcoredistools`
echo "libPath to be used: ${libPath}"

if [ ! -e $libPath ] || [ -z "$libPath" ]; then
    exit_with_error 1 'Failed to locate the downloaded library'
fi

# Copy library to output directory
echo 'Copy library:' $libPath '-->' $libInstallDir/
cp -f $libPath $libInstallDir
if [ $? -ne 0 ]
then
    exit_with_error 1 "Failed to copy the library"
fi

# Return success
exit $EXIT_CODE_SUCCESS


text:
description: Template Archive
keywords: azure, microsoft, iaas, release, edge, stable
title: Docker for Azure template archive
---

Azure Resource Manager (ARM) templates for past releases. If you are just
starting out, use the latest version.

## CE (Stable)

### 17.06.2

https://download.docker.com/azure/stable/17.06.2/Docker.tmpl

## EE

### 17.06.2

 * Docker EE Basic: https://download.docker.com/azure/17.06/17.06.2/Docker-EE.tmpl
 * Docker EE Standard and Advanced: https://download.docker.com/azure/17.06/17.06.2/Docker-DDC.tmpl

### 17.03.2

https://download.docker.com/azure/17.03/17.03.2/Docker.tmpl


text:
d3.geo.greatArc = function() {
  var source = d3_source, s,
      target = d3_target, t,
      precision = 6 * d3_radians,
      interpolate;

  function greatArc() {
    var p0 = s || source.apply(this, arguments),
        p1 = t || target.apply(this, arguments),
        i = interpolate || d3.geo.interpolate(p0, p1),
        t = 0,
        dt = precision / i.distance,
        coordinates = [p0];
    while ((t += dt) < 1) coordinates.push(i(t));
    coordinates.push(p1);
    return {type: "LineString", coordinates: coordinates};
  }

  // Length returned in radians; multiply by radius for distance.
  greatArc.distance = function() {
    return (interpolate || d3.geo.interpolate(s || source.apply(this, arguments), t || target.apply(this, arguments))).distance;
  };

  greatArc.source = function(_) {
    if (!arguments.length) return source;
    source = _, s = typeof _ === "function" ? null : _;
    interpolate = s && t ? d3.geo.interpolate(s, t) : null;
    return greatArc;
  };

  greatArc.target = function(_) {
    if (!arguments.length) return target;
    target = _, t = typeof _ === "function" ? null : _;
    interpolate = s && t ? d3.geo.interpolate(s, t) : null;
    return greatArc;
  };

  // Precision is specified in degrees.
  greatArc.precision = function(_) {
    if (!arguments.length) return precision / d3_radians;
    precision = _ * d3_radians;
    return greatArc;
  };

  return greatArc;
};


text:
package org.apache.sysml.hops;

import org.apache.sysml.conf.ConfigurationManager;
import org.apache.sysml.lops.Binary;
import org.apache.sysml.lops.Group;
import org.apache.sysml.lops.LeftIndex;
import org.apache.sysml.lops.LeftIndex.LixCacheType;
import org.apache.sysml.lops.Lop;
import org.apache.sysml.lops.LopsException;
import org.apache.sysml.lops.RightIndex;
import org.apache.sysml.lops.UnaryCP;
import org.apache.sysml.lops.ZeroOut;
import org.apache.sysml.lops.LopProperties.ExecType;
import org.apache.sysml.lops.UnaryCP.OperationTypes;
import org.apache.sysml.parser.Expression.DataType;
import org.apache.sysml.parser.Expression.ValueType;
import org.apache.sysml.runtime.matrix.MatrixCharacteristics;

public class LeftIndexingOp  extends Hop
{
	public static LeftIndexingMethod FORCED_LEFT_INDEXING = null;

	public enum LeftIndexingMethod {
		SP_GLEFTINDEX,   //general case
		SP_MLEFTINDEX_R, //map-only left index, broadcast rhs
		SP_MLEFTINDEX_L, //map-only left index, broadcast lhs
	}

	public static String OPSTRING = "lix"; //"LeftIndexing";

	private boolean _rowLowerEqualsUpper = false;
	private boolean _colLowerEqualsUpper = false;

	private LeftIndexingOp() {
		//default constructor for clone
	}

	public LeftIndexingOp(String l, DataType dt, ValueType vt, Hop inpMatrixLeft, Hop inpMatrixRight, Hop inpRowL, Hop inpRowU, Hop inpColL, Hop inpColU, boolean passedRowsLEU, boolean passedColsLEU) {
		super(l, dt, vt);

		getInput().add(0, inpMatrixLeft);
		getInput().add(1, inpMatrixRight);
		getInput().add(2, inpRowL);
		getInput().add(3, inpRowU);
		getInput().add(4, inpColL);
		getInput().add(5, inpColU);

		// create hops if one of them is null
		inpMatrixLeft.getParent().add(this);
		inpMatrixRight.getParent().add(this);
		inpRowL.getParent().add(this);
		inpRowU.getParent().add(this);
		inpColL.getParent().add(this);
		inpColU.getParent().add(this);

		// set information whether left indexing operation involves row (n x 1) or column (1 x m) matrix
		setRowLowerEqualsUpper(passedRowsLEU);
		setColLowerEqualsUpper(passedColsLEU);
	}

	@Override
	public void checkArity() throws HopsException {
		HopsException.check(_input.size() == 6, this, "should have 6 inputs but has %d inputs", 6);
	}

	public boolean isRowLowerEqualsUpper(){
		return _rowLowerEqualsUpper;
	}

	public boolean isColLowerEqualsUpper() {
		return _colLowerEqualsUpper;
	}

	public void setRowLowerEqualsUpper(boolean passed){
		_rowLowerEqualsUpper  = passed;
	}

	public void setColLowerEqualsUpper(boolean passed) {
		_colLowerEqualsUpper = passed;
	}

	@Override
	public boolean isGPUEnabled() {
		return false;
	}

	@Override
	public Lop constructLops()
		throws HopsException, LopsException
	{
		//return already created lops
		if( getLops() != null )
			return getLops();

		try
		{
			ExecType et = optFindExecType();

			if(et == ExecType.MR)
			{
				//the right matrix is reindexed
				Lop top=getInput().get(2).constructLops();
				Lop bottom=getInput().get(3).constructLops();
				Lop left=getInput().get(4).constructLops();
				Lop right=getInput().get(5).constructLops();

				//right hand matrix
				Lop nrow=new UnaryCP(getInput().get(0).constructLops(),
								OperationTypes.NROW, DataType.SCALAR, ValueType.INT);
				Lop ncol=new UnaryCP(getInput().get(0).constructLops(),
										OperationTypes.NCOL, DataType.SCALAR, ValueType.INT);

				Lop rightInput = null;
				if (isRightHandSideScalar()) {
					//insert cast to matrix if necessary (for reuse MR runtime)
					rightInput = new UnaryCP(getInput().get(1).constructLops(),
							                 OperationTypes.CAST_AS_MATRIX,
							                 DataType.MATRIX, ValueType.DOUBLE);
					rightInput.getOutputParameters().setDimensions( (long)1, (long)1,
																	(long)ConfigurationManager.getBlocksize(),
							                                        (long)ConfigurationManager.getBlocksize(),
							                                        (long)-1);
				}
				else
					rightInput = getInput().get(1).constructLops();

				RightIndex reindex = new RightIndex(
						rightInput, top, bottom,
						left, right, nrow, ncol,
						getDataType(), getValueType(), et, true);

				reindex.getOutputParameters().setDimensions(getInput().get(0).getDim1(), getInput().get(0).getDim2(),
						getRowsInBlock(), getColsInBlock(), getNnz());
				setLineNumbers(reindex);

				Group group1 = new Group(
						reindex, Group.OperationTypes.Sort, DataType.MATRIX,
						getValueType());
				group1.getOutputParameters().setDimensions(getInput().get(0).getDim1(), getInput().get(0).getDim2(),
						getRowsInBlock(), getColsInBlock(), getNnz());
				setLineNumbers(group1);

				//the left matrix is zeroed out
				ZeroOut zeroout = new ZeroOut(
						getInput().get(0).constructLops(), top, bottom,
						left, right, getInput().get(0).getDim1(), getInput().get(0).getDim2(),
						getDataType(), getValueType(), et);
				zeroout.getOutputParameters().setDimensions(getInput().get(0).getDim1(), getInput().get(0).getDim2(),
						getRowsInBlock(), getColsInBlock(), getNnz());
				setLineNumbers(zeroout);

				Group group2 = new Group(
						zeroout, Group.OperationTypes.Sort, DataType.MATRIX,
						getValueType());
				group2.getOutputParameters().setDimensions(getInput().get(0).getDim1(), getInput().get(0).getDim2(),
						getRowsInBlock(), getColsInBlock(), getNnz());
				setLineNumbers(group2);

				Binary binary = new Binary(group1, group2, HopsOpOp2LopsB.get(Hop.OpOp2.PLUS),
						getDataType(), getValueType(), et);
				binary.getOutputParameters().setDimensions(getInput().get(0).getDim1(), getInput().get(0).getDim2(),
						getRowsInBlock(), getColsInBlock(), getNnz());
				setLineNumbers(binary);

				setLops(binary);
			}
			else if(et == ExecType.SPARK)
			{
				Hop left = getInput().get(0);
				Hop right = getInput().get(1);

				LeftIndexingMethod method = getOptMethodLeftIndexingMethod(
						left.getDim1(), left.getDim2(), left.getRowsInBlock(), left.getColsInBlock(), left.getNnz(),
						right.getDim1(), right.getDim2(), right.getNnz(), right.getDataType() );

				//insert cast to matrix if necessary (for reuse broadcast runtime)
				Lop rightInput = right.constructLops();
				if (isRightHandSideScalar()) {
					rightInput = new UnaryCP(rightInput, (left.getDataType()==DataType.MATRIX?OperationTypes.CAST_AS_MATRIX:OperationTypes.CAST_AS_FRAME),
											left.getDataType(), right.getValueType());
					long bsize = ConfigurationManager.getBlocksize();
					rightInput.getOutputParameters().setDimensions( 1, 1, bsize, bsize, -1);
				}

				LeftIndex leftIndexLop = new LeftIndex(
						left.constructLops(), rightInput,
						getInput().get(2).constructLops(), getInput().get(3).constructLops(),
						getInput().get(4).constructLops(), getInput().get(5).constructLops(),
						getDataType(), getValueType(), et, getSpLixCacheType(method));

				setOutputDimensions(leftIndexLop);
				setLineNumbers(leftIndexLop);
				setLops(leftIndexLop);
			}
			else
			{
				LeftIndex left = new LeftIndex(
						getInput().get(0).constructLops(), getInput().get(1).constructLops(), getInput().get(2).constructLops(),
						getInput().get(3).constructLops(), getInput().get(4).constructLops(), getInput().get(5).constructLops(),
						getDataType(), getValueType(), et);

				setOutputDimensions(left);
				setLineNumbers(left);
				setLops(left);
			}
		}
		catch (Exception e) {
			throw new HopsException(this.printErrorLocation() + "In LeftIndexingOp Hop, error in constructing Lops " , e);
		}

		//add reblock/checkpoint lops if necessary
		constructAndSetLopsDataFlowProperties();

		return getLops();
	}

	/**
	 * @return true if the right hand side of the indexing operation is a
	 *         literal.
	 */
	private boolean isRightHandSideScalar() {
		Hop rightHandSide = getInput().get(1);
		return (rightHandSide.getDataType() == DataType.SCALAR);
	}

	private LixCacheType getSpLixCacheType(LeftIndexingMethod method) {
		switch( method ) {
			case SP_MLEFTINDEX_L: return LixCacheType.LEFT;
			case SP_MLEFTINDEX_R: return LixCacheType.RIGHT;
			default: return LixCacheType.NONE;
		}
	}

	@Override
	public String getOpString() {
		String s = new String("");
		s += OPSTRING;
		return s;
	}

	@Override
	public boolean allowsAllExecTypes()
	{
		return false;
	}

	@Override
	public void computeMemEstimate( MemoTable memo )
	{
		//overwrites default hops behavior
		super.computeMemEstimate(memo);

		//changed final estimate (infer and use input size)
		Hop rhM = getInput().get(1);
		MatrixCharacteristics mcRhM = memo.getAllInputStats(rhM);
		//TODO also use worstcase estimate for output
		if( dimsKnown() && !(rhM.dimsKnown()||mcRhM.dimsKnown()) )
		{
			// unless second input is single cell / row vector / column vector
			// use worst-case memory estimate for second input (it cannot be larger than overall matrix)
			double subSize = -1;
			if( _rowLowerEqualsUpper && _colLowerEqualsUpper )
				subSize = OptimizerUtils.estimateSize(1, 1);
			else if( _rowLowerEqualsUpper )
				subSize = OptimizerUtils.estimateSize(1, _dim2);
			else if( _colLowerEqualsUpper )
				subSize = OptimizerUtils.estimateSize(_dim1, 1);
			else
				subSize = _outputMemEstimate; //worstcase

			_memEstimate = getInputSize(0) //original matrix (left)
			               + subSize // new submatrix (right)
			               + _outputMemEstimate; //output size (output)
		}
		else if ( dimsKnown() && _nnz<0 &&
				  _memEstimate>=OptimizerUtils.DEFAULT_SIZE)
		{
			//try a last attempt to infer a reasonable estimate wrt output sparsity
			//(this is important for indexing sparse matrices into empty matrices).
			MatrixCharacteristics mcM1 = memo.getAllInputStats(getInput().get(0));
			MatrixCharacteristics mcM2 = memo.getAllInputStats(getInput().get(1));
			if( mcM1.getNonZeros()>=0 && mcM2.getNonZeros()>=0
				&& hasConstantIndexingRange() )
			{
				long lnnz = mcM1.getNonZeros() + mcM2.getNonZeros();
				_outputMemEstimate = computeOutputMemEstimate( _dim1, _dim2, lnnz );
				_memEstimate = getInputSize(0) //original matrix (left)
			                 + getInputSize(1) // new submatrix (right)
			                 + _outputMemEstimate; //output size (output)
			}
		}
	}

	@Override
	protected double computeOutputMemEstimate( long dim1, long dim2, long nnz )
	{
		double sparsity = 1.0;
		if( nnz < 0 ) //check for exactly known nnz
		{
			Hop input1 = getInput().get(0);
			Hop input2 = getInput().get(1);
			if( input1.dimsKnown() && hasConstantIndexingRange() ) {
				sparsity = OptimizerUtils.getLeftIndexingSparsity(
						input1.getDim1(), input1.getDim2(), input1.getNnz(),
						input2.getDim1(), input2.getDim2(), input2.getNnz());
			}
		}
		else
		{
			sparsity = OptimizerUtils.getSparsity(dim1, dim2, nnz);
		}

		// The dimensions of the left indexing output is same as that of the first input i.e., getInput().get(0)
		return OptimizerUtils.estimateSizeExactSparsity(dim1, dim2, sparsity);
	}

	@Override
	protected double computeIntermediateMemEstimate( long dim1, long dim2, long nnz )
	{
		return 0;
	}

	@Override
	protected long[] inferOutputCharacteristics( MemoTable memo )
	{
		long[] ret = null;

		Hop input1 = getInput().get(0); //original matrix
		Hop input2 = getInput().get(1); //right matrix
		MatrixCharacteristics mc1 = memo.getAllInputStats(input1);
		MatrixCharacteristics mc2 = memo.getAllInputStats(input2);

		if( mc1.dimsKnown() ) {
			double sparsity = OptimizerUtils.getLeftIndexingSparsity(
					mc1.getRows(), mc1.getCols(), mc1.getNonZeros(),
					mc2.getRows(), mc2.getCols(), mc2.getNonZeros());
			long lnnz = !hasConstantIndexingRange() ? -1 :
					(long)(sparsity * mc1.getRows() * mc1.getCols());
			ret = new long[]{mc1.getRows(), mc1.getCols(), lnnz};
		}

		return ret;
	}

	@Override
	protected ExecType optFindExecType() throws HopsException {

		checkAndSetForcedPlatform();

		ExecType REMOTE = OptimizerUtils.isSparkExecutionMode() ? ExecType.SPARK : ExecType.MR;

		if( _etypeForced != null )
		{
			_etype = _etypeForced;
		}
		else
		{
			if ( OptimizerUtils.isMemoryBasedOptLevel() ) {
				_etype = findExecTypeByMemEstimate();
				checkAndModifyRecompilationStatus();
			}
			else if ( getInput().get(0).areDimsBelowThreshold() )
			{
				_etype = ExecType.CP;
			}
			else
			{
				_etype = REMOTE;
			}

			//check for valid CP dimensions and matrix size
			checkAndSetInvalidCPDimsAndSize();
		}

		//mark for recompile (forever)
		setRequiresRecompileIfNecessary();

		return _etype;
	}

	private static LeftIndexingMethod getOptMethodLeftIndexingMethod(
			long m1_dim1, long m1_dim2, long m1_rpb, long m1_cpb, long m1_nnz,
			long m2_dim1, long m2_dim2, long m2_nnz, DataType rhsDt)
	{
		if(FORCED_LEFT_INDEXING != null) {
			return FORCED_LEFT_INDEXING;
		}

		// broadcast-based left indexing w/o shuffle for scalar rhs
		if( rhsDt == DataType.SCALAR ) {
			return LeftIndexingMethod.SP_MLEFTINDEX_R;
		}

		// broadcast-based left indexing w/o shuffle for small left/right inputs
		if( m2_dim1 >= 1 && m2_dim2 >= 1 && m2_dim1 >= 1 && m2_dim2 >= 1 ) { //lhs/rhs known
			boolean isAligned = (rhsDt == DataType.MATRIX) &&
					((m1_dim1 == m2_dim1 && m1_dim2 <= m1_cpb) || (m1_dim2 == m2_dim2 && m1_dim1 <= m1_rpb));
			boolean broadcastRhs = OptimizerUtils.checkSparkBroadcastMemoryBudget(m2_dim1, m2_dim2, m1_rpb, m1_cpb, m2_nnz);
			double m1SizeP = OptimizerUtils.estimatePartitionedSizeExactSparsity(m1_dim1, m1_dim2, m1_rpb, m1_cpb, m1_nnz);
			double m2SizeP = OptimizerUtils.estimatePartitionedSizeExactSparsity(m2_dim1, m2_dim2, m1_rpb, m1_cpb, m2_nnz);

			if( broadcastRhs ) {
				if( isAligned && m1SizeP<m2SizeP ) //e.g., sparse-dense lix
					return LeftIndexingMethod.SP_MLEFTINDEX_L;
				else //all other cases, where rhs smaller than lhs
					return LeftIndexingMethod.SP_MLEFTINDEX_R;
			}
		}

		// default general case
		return LeftIndexingMethod.SP_GLEFTINDEX;
	}

	@Override
	public void refreshSizeInformation()
	{
		Hop input1 = getInput().get(0);	//original matrix
		Hop input2 = getInput().get(1); //rhs matrix

		//refresh output dimensions based on original matrix
		setDim1( input1.getDim1() );
		setDim2( input1.getDim2() );

		//refresh output nnz if exactly known; otherwise later inference
		//note: leveraging the nnz for estimating the output sparsity is
		//only valid for constant index identifiers (e.g., after literal
		//replacement during dynamic recompilation), otherwise this could
		//lead to underestimation and hence OOMs in loops
		if( input1.getNnz() == 0 && hasConstantIndexingRange() )  {
			if( input2.getDataType()==DataType.SCALAR )
				setNnz(1);
			else
				setNnz(input2.getNnz());
		}
		else
			setNnz(-1);
	}

	private boolean hasConstantIndexingRange() {
		return (getInput().get(2) instanceof LiteralOp
			&& getInput().get(3) instanceof LiteralOp
			&& getInput().get(4) instanceof LiteralOp
			&& getInput().get(5) instanceof LiteralOp);
	}

	private void checkAndModifyRecompilationStatus()
	{
		// disable recompile for LIX and second input matrix (under certain conditions)
		// if worst-case estimate (2 * original matrix size) was enough to already send it to CP

		if( _etype == ExecType.CP )
		{
			_requiresRecompile = false;

			Hop rInput = getInput().get(1);
			if( (!rInput.dimsKnown()) && rInput instanceof DataOp  )
			{
				//disable recompile for this dataop (we cannot set requiresRecompile directly
				//because we use a top-down traversal for creating lops, hence it would be overwritten)

				((DataOp)rInput).disableRecompileRead();
			}
		}
	}

	@Override
	public Object clone() throws CloneNotSupportedException
	{
		LeftIndexingOp ret = new LeftIndexingOp();

		//copy generic attributes
		ret.clone(this, false);

		//copy specific attributes

		return ret;
	}

	@Override
	public boolean compare( Hop that )
	{
		if(    !(that instanceof LeftIndexingOp)
			|| getInput().size() != that.getInput().size() )
		{
			return false;
		}

		return (  getInput().get(0) == that.getInput().get(0)
				&& getInput().get(1) == that.getInput().get(1)
				&& getInput().get(2) == that.getInput().get(2)
				&& getInput().get(3) == that.getInput().get(3)
				&& getInput().get(4) == that.getInput().get(4)
				&& getInput().get(5) == that.getInput().get(5));
	}

}


text:
<devicedata>
  <copyright>Copyright 2016 Pulse-Eight Limited.  All rights reserved.</copyright>
  <creator>Pulse-Eight</creator>
  <manufacturer>Pulse-Eight</manufacturer>
  <name>neo:8 Modular IP Driver</name>
  <model>neo:8 Modular</model>
  <created>08/14/2015 10:39 PM</created>
  <modified>18/07/2016 3:58 PM</modified>
  <OnlineCategory>AVSwitch</OnlineCategory>
  <version>30</version>
  <small>assets\neo_sm.gif</small>
  <large>assets\neo_lg.gif</large>
  <control>lua_gen</control>
  <controlmethod>ip</controlmethod>
  <driver>DriverWorks</driver>
  <search_types>
    <type>c4:av_gen</type>
  </search_types>
  <proxies>
    <proxy proxybindingid="5001" name="neo:8 Modular">avswitch</proxy>
  </proxies>
  <capabilities>
    <audio_consumer_count>0</audio_consumer_count>
    <audio_provider_count>0</audio_provider_count>
    <can_downclass>False</can_downclass>
    <can_switch>True</can_switch>
    <can_upclass>False</can_upclass>
    <has_audio_sense_control>False</has_audio_sense_control>
    <has_discrete_balance_control>False</has_discrete_balance_control>
    <has_discrete_bass_control>False</has_discrete_bass_control>
    <has_discrete_input_select>True</has_discrete_input_select>
    <has_discrete_loudness_control>False</has_discrete_loudness_control>
    <has_discrete_mute_control>False</has_discrete_mute_control>
    <has_discrete_treble_control>False</has_discrete_treble_control>
    <has_discrete_volume_control>False</has_discrete_volume_control>
    <has_toad_input_select>False</has_toad_input_select>
    <has_toggle_loudness_control>False</has_toggle_loudness_control>
    <has_toggle_mute_control>False</has_toggle_mute_control>
    <has_up_down_balance_control>False</has_up_down_balance_control>
    <has_up_down_bass_control>False</has_up_down_bass_control>
    <has_up_down_treble_control>False</has_up_down_treble_control>
    <has_video_sense_control>False</has_video_sense_control>
    <video_consumer_count>8</video_consumer_count>
    <video_provider_count>8</video_provider_count>
    <can_switch_separately>false</can_switch_separately>
    <requires_separate_switching>false</requires_separate_switching>
    <has_up_down_volume_control>false</has_up_down_volume_control>
  </capabilities>
  <connections>
    <connection>
      <id>5001</id>
      <type>2</type>
      <connectionname>AVSWITCH</connectionname>
      <consumer>False</consumer>
      <linelevel>True</linelevel>
      <classes>
        <class>
          <classname>AVSWITCH</classname>
        </class>
      </classes>
    </connection>
    <connection>
      <id>1000</id>
      <type>5</type>
      <connectionname>Input 1</connectionname>
      <consumer>true</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>1001</id>
      <type>5</type>
      <connectionname>Input 2</connectionname>
      <consumer>true</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>1002</id>
      <type>5</type>
      <connectionname>Input 3</connectionname>
      <consumer>true</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>1003</id>
      <type>5</type>
      <connectionname>Input 4</connectionname>
      <consumer>true</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>1004</id>
      <type>5</type>
      <connectionname>Input 5</connectionname>
      <consumer>true</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>1005</id>
      <type>5</type>
      <connectionname>Input 6</connectionname>
      <consumer>true</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>1006</id>
      <type>5</type>
      <connectionname>Input 7</connectionname>
      <consumer>true</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>1007</id>
      <type>5</type>
      <connectionname>Input 8</connectionname>
      <consumer>true</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>2000</id>
      <type>5</type>
      <connectionname>Output 1</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>2001</id>
      <type>5</type>
      <connectionname>Output 2</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>2002</id>
      <type>5</type>
      <connectionname>Output 3</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>2003</id>
      <type>5</type>
      <connectionname>Output 4</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>2004</id>
      <type>5</type>
      <connectionname>Output 5</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>2005</id>
      <type>5</type>
      <connectionname>Output 6</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>2006</id>
      <type>5</type>
      <connectionname>Output 7</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>2007</id>
      <type>5</type>
      <connectionname>Output 8</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>HDMI</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>7000</id>
      <type>7</type>
      <connectionname>Room 1</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>AUDIO_SELECTION</classname>
        </class>
        <class>
          <classname>VIDEO_SELECTION</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>7001</id>
      <type>7</type>
      <connectionname>Room 2</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>AUDIO_SELECTION</classname>
        </class>
        <class>
          <classname>VIDEO_SELECTION</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>7002</id>
      <type>7</type>
      <connectionname>Room 3</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>AUDIO_SELECTION</classname>
        </class>
        <class>
          <classname>VIDEO_SELECTION</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>7003</id>
      <type>7</type>
      <connectionname>Room 4</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>AUDIO_SELECTION</classname>
        </class>
        <class>
          <classname>VIDEO_SELECTION</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>7004</id>
      <type>7</type>
      <connectionname>Room 5</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>AUDIO_SELECTION</classname>
        </class>
        <class>
          <classname>VIDEO_SELECTION</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>7005</id>
      <type>7</type>
      <connectionname>Room 6</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>AUDIO_SELECTION</classname>
        </class>
        <class>
          <classname>VIDEO_SELECTION</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>7006</id>
      <type>7</type>
      <connectionname>Room 7</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>AUDIO_SELECTION</classname>
        </class>
        <class>
          <classname>VIDEO_SELECTION</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
    <connection>
      <id>7007</id>
      <type>7</type>
      <connectionname>Room 8</connectionname>
      <consumer>false</consumer>
      <linelevel>true</linelevel>
      <classes>
        <class>
          <classname>AUDIO_SELECTION</classname>
        </class>
        <class>
          <classname>VIDEO_SELECTION</classname>
        </class>
      </classes>
      <facing>1</facing>
    </connection>
  </connections>
  <config>
    <actions>
      <action>
        <name>Reboot System</name>
        <command>REBOOT</command>
      </action>
      <action>
        <name>Discover System</name>
        <command>DISCOVER</command>
      </action>
      <action>
        <name>Send Monitoring Pulse</name>
        <command>SENDPULSE</command>
      </action>
    </actions>
    <power_management_method>AlwaysOn</power_management_method>
    <power_command_delay>0</power_command_delay>
    <power_delay>0</power_delay>
    <power_command_needed>False</power_command_needed>
    <serialsettings>9600 8 none 1 none 232</serialsettings>
    <documentation file="documentation.rtf" />
    <script file="p8driver.lua" />
    <properties>
      <property>
        <name>Device IP Address</name>
        <type>STRING</type>
        <readonly>false</readonly>
        <default>[Goto Action Tab and Click Discover System]</default>
        <tooltip>If you are unsure of the IP address of your matrix, enter www.gotomymatrix.com to be redirected to the web UI, copy the IP from your browser into this box</tooltip>
        <description>The IP address of your neo matrix, this in many cases can be auto discovered via the action tab button "Discover System". If this fails, enter www.gotomymatrix.com into your browser for more information.</description>
      </property>
      <property>
        <name>Log Level</name>
        <type>LIST</type>
        <readonly>false</readonly>
        <default>2 - Warning</default>
        <items>
          <item>0 - Alert</item>
          <item>1 - Error</item>
          <item>2 - Warning</item>
          <item>3 - Info</item>
          <item>4 - Trace</item>
          <item>5 - Debug</item>
        </items>
      </property>
      <property>
        <name>Log Mode</name>
        <type>LIST</type>
        <readonly>false</readonly>
        <default>Off</default>
        <items>
          <item>Off</item>
          <item>Print</item>
          <item>Log</item>
          <item>Print and Log</item>
        </items>
      </property>
      <property>
        <name>Connected To Network</name>
        <type>STRING</type>
        <readonly>true</readonly>
        <default>No</default>
      </property>
      <property>
        <name>System Status</name>
        <type>STRING</type>
        <readonly>true</readonly>
        <default>Unknown</default>
      </property>
      <property>
        <name>Installer Id</name>
        <type>RANGED_INTEGER</type>
        <minimum>1000</minimum>
        <maximum>9999</maximum>
        <readonly>false</readonly>
        <default>9999</default>
      </property>
      <property>
        <name>Model</name>
        <type>STRING</type>
        <readonly>true</readonly>
        <default>Unknown</default>
      </property>
      <property>
        <name>Version</name>
        <type>STRING</type>
        <readonly>true</readonly>
        <default>Unknown</default>
      </property>
      <property>
        <name>Serial</name>
        <type>STRING</type>
        <readonly>true</readonly>
        <default>Unknown</default>
      </property>
      <property>
        <name>System Uptime</name>
        <type>STRING</type>
        <readonly>true</readonly>
        <default>Unknown</default>
      </property>
    </properties>
  </config>
  <composer_categories>
    <category>Audio/Video</category>
  </composer_categories>
</devicedata>


text:
<meta charset="UTF-8">
<title>RInAppBilling.PURCHASE_SUCCESS - RichUtils</title>
<link rel="stylesheet" href="../../../style.css">

RichUtils / pyxis.uzuki.live.richutilskt.module.iap / RInAppBilling / PURCHASE_SUCCESS

PURCHASE_SUCCESS

@JvmField val PURCHASE_SUCCESS: Int


text:
[![Carthage compatible](https://img.shields.io/badge/Carthage-compatible-4BC51D.svg?style=flat)](https://github.com/Carthage/Carthage)

### GCDTimer ###
Well tested Grand Central Dispatch (GCD) Timer in Swift. Checkout the [test](GCDTimerTests/GCDTimerTests.swift) file.

### Usage ###

#### Long running timer ####
```swift
import GCDTimer

class Demo {

  init() {
    let timer = GCDTimer(intervalInSecs: 20)

    timer.Event = {
      println("Hello World")

      // Send some data to the server
    }

    timer.start()

    //Don't forget to pause the timer in the AppDelegate:applicationWillResignActive(application: UIApplication) method.
  }

}

```

#### Autofinishing timer ####

```swift
import GCDTimer

class Demo {

  init() {
    let timer = GCDTimer(intervalInSecs: 2)

    timer.Event = {
      timer.pause()
      //Process after finishing the timer
    }

    timer.start()
  }

}
```

#### Dispatch After - Delay ####

```swift
var index = 0
GCDTimer.delay(2) {
    index += 1
}
```

### Installation ###

* Add ```github "hemantasapkota/GCDTimer"``` to your ```cartfile```
* Execute ```carthage update```

### Example ###
The example shows how to use GCDTimer to periodically poll newly submitted items from Hacker News.

![ExampleSS](Example/GCDTimerExample/ExampleSS.png)

### License ###
The MIT License (MIT)

Copyright (c) 2022 Hemanta Sapkota

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.


text:
title: SharePoint-tu internet ichil-k1
inshort: undefined
translator: Microsoft Cognitive Services
---


text:
package bt.net.buffer;

import bt.runtime.Config;
import com.google.inject.Inject;

import java.lang.ref.SoftReference;
import java.nio.Buffer;
import java.nio.ByteBuffer;
import java.util.Deque;
import java.util.Objects;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.LinkedBlockingDeque;
import java.util.concurrent.locks.ReentrantLock;

public class BufferManager implements IBufferManager {

    private ConcurrentMap<Class<?>, Deque<SoftReference<?>>> releasedBuffers;

    private final int bufferSize;

    @Inject
    public BufferManager(Config config) {
        this.bufferSize = config.getNetworkBufferSize();
        this.releasedBuffers = new ConcurrentHashMap<>();
    }

    @Override
    @SuppressWarnings("unchecked")
    public BorrowedBuffer<ByteBuffer> borrowByteBuffer() {
        Deque<SoftReference<?>> deque = getReleasedBuffersDeque(ByteBuffer.class);
        SoftReference<ByteBuffer> ref;
        ByteBuffer buffer = null;
        do {
            ref = (SoftReference<ByteBuffer>) deque.pollLast();
            if (ref != null) {
                buffer = ref.get();
            }
            // check if the referenced buffer has been garbage collected
        } while (ref != null && buffer == null);

        if (buffer == null) {
            buffer = ByteBuffer.allocateDirect(bufferSize);
        } else {
            // reset buffer before re-using
            buffer.clear();
        }
        return new DefaultBorrowedBuffer<>(buffer);
    }

    private <T extends Buffer> Deque<SoftReference<?>> getReleasedBuffersDeque(Class<T> bufferType) {
        return releasedBuffers.computeIfAbsent(bufferType, it -> new LinkedBlockingDeque<>());
    }

    private class DefaultBorrowedBuffer<T extends Buffer> implements BorrowedBuffer<T> {

        private volatile T buffer;
        private final ReentrantLock lock;

        DefaultBorrowedBuffer(T buffer) {
            this.buffer = Objects.requireNonNull(buffer);
            this.lock = new ReentrantLock();
        }

        @Override
        public T lockAndGet() {
            lock.lock();
            return buffer;
        }

        @Override
        public void unlock() {
            lock.unlock();
        }

        @Override
        public void release() {
            lock.lock();
            try {
                if (buffer != null) {
                    // check if lockAndGet() has been called by the current thread and not followed by unlock()
                    if (lock.getHoldCount() > 1) {
                        throw new IllegalStateException("Buffer is locked and can't be released");
                    }
                    if (buffer != null) {
                        getReleasedBuffersDeque(ByteBuffer.class).add(new SoftReference<>(buffer));
                        buffer = null;
                    }
                }
            } finally {
                lock.unlock();
            }
        }
    }
}


text:
Exploring the capabilities of the Muse Headband
============

https://sites.google.com/a/interaxon.ca/muse-developer-site/home

Demo: https://www.youtube.com/watch?v=-lCQAi0NKIc

muse-node
=========

visualize your brainwave activity in the browser.

<a href="https://www.youtube.com/watch?v=-lCQAi0NKIc">
![image](https://cloud.githubusercontent.com/assets/39191/4486873/75f7baaa-49ee-11e4-8828-60289bff5c7e.png)
</a>

![image](http://i.imgur.com/diQk2Gf.gif)

# Running

* Get the [muse headband](http://www.choosemuse.com/)
* Get the [muse sdk](https://sites.google.com/a/interaxon.ca/muse-developer-site/download/macos-install---sdk-v2-2)
* Pair your device
* Run [muse-io](https://sites.google.com/a/interaxon.ca/muse-developer-site/museio/tutorial).
  * For example: `muse-io --preset 14 --device Muse --osc osc.udp://localhost:5000`
  * You should be seeing something like ![image](https://cloud.githubusercontent.com/assets/39191/4486860/32465e9c-49ee-11e4-83ee-13d7e8611cf7.png)
* You might have to reinstall the node-serialport package to get a binary built for your machine. This repo right now handles mac only.
  * You'll get an error from the next step if you do. :)
* Run `node server.js`
* Serve the public folder
* You should be getting a live D3 visual of your brainwave EEG.

![image](https://cloud.githubusercontent.com/assets/39191/4486882/c09f2fde-49ee-11e4-81c2-53c6039b585f.png)

# Who

- Inital app work: [bobi-rakova](https://github.com/bobi-rakova/muse)
- Readme updates: [paulirish](https://github.com/paulirish/muse-node)
- Animated GIF: [derekbreden](https://github.com/derekbreden/muse-node)
- Updates to structure [JamesHagerman](https://github.com/JamesHagerman/muse-node)


text:
import pytest
from rig_remote.stmessenger import STMessenger
from mock import Mock, MagicMock

fake_event_list=[("test"), ([1,2,3])]
@pytest.mark.parametrize("fake_event", fake_event_list)
def test_wrong_event_update(fake_event):
    fake=fake_event
    stm = STMessenger()
    with pytest.raises(ValueError):
        stm.send_event_update(fake)

def test_good_event_update():
    fake=(1,2)
    stm = STMessenger()
    assert (stm.send_event_update(fake) == None)

def test_end_of_scan1():
    stm = STMessenger()
    assert (stm.check_end_of_scan() == False)

def test_end_of_scan2():
    stm = STMessenger()
    stm.notify_end_of_scan()
    assert (stm.check_end_of_scan() == True)

def test_empty_get_event_update():
    stm = STMessenger()
    stm.mqueue.get_from_child = MagicMock()
    stm.mqueue.get_from_child.return_value = None
    assert (stm.get_event_update() == None)

def test_error_get_event_update():
    stm = STMessenger()
    stm.mqueue.get_from_child = MagicMock(side_effect=Exception)
    assert (stm.get_event_update() == [])


text:
<?php

use Illuminate\Database\Schema\Blueprint;
use Illuminate\Database\Migrations\Migration;

class CreateOrderProduct extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('order_product', function(Blueprint $table){
            $table->increments('id');
            $table->integer('quantity');
            $table->integer('state');
            $table->integer('value');
            $table->integer('order_id')->unsigned();
            $table->integer('product_id')->unsigned();
            $table->timestamps();

            $table->foreign('order_id')->references('id')->on('orders');
            $table->foreign('product_id')->references('id')->on('products');
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::dropIfExists('order_product');
    }
}


text:
{% extends 'main/base.html' %}
{% block content %}

{% if validlink %}

Hello, {{ form.user }}.

Please enter your new password twice so we can verify you typed it in correctly.

<form action="" method="post">
{% csrf_token %}
{{ form.new_password1.errors }}

New password:{{ form.new_password1 }}

{{ form.new_password2.errors }}

Confirm password:{{ form.new_password2 }}

<input type="submit" class="btn btn-danger" value="Change my password" />

</form>
{% else %}

The password reset link was invalid, possibly because it has already been used. Please request a new password reset.

{% endif %}

{% endblock %}


text:
[![Build Status](http://img.shields.io/travis/silverstripe-labs/silverstripe-sharedraftcontent.svg?style=flat-square)](https://travis-ci.org/silverstripe-labs/silverstripe-sharedraftcontent)
[![Code Quality](http://img.shields.io/scrutinizer/g/silverstripe-labs/silverstripe-sharedraftcontent.svg?style=flat-square)](https://scrutinizer-ci.com/g/silverstripe-labs/silverstripe-sharedraftcontent)
[![Code Coverage](http://img.shields.io/scrutinizer/coverage/g/silverstripe-labs/silverstripe-sharedraftcontent.svg?style=flat-square)](https://scrutinizer-ci.com/g/silverstripe-labs/silverstripe-sharedraftcontent)
[![Version](http://img.shields.io/packagist/v/silverstripe/sharedraftcontent.svg?style=flat-square)](https://packagist.org/packages/silverstripe/silverstripe-sharedraftcontent)
[![License](http://img.shields.io/packagist/l/silverstripe/sharedraftcontent.svg?style=flat-square)](LICENSE.md)

Share draft page content with non-CMS users.

## Overview

This module adds a 'Share draft' action menu to the CMS. This enables Content Authors to generate tokenised links to draft pages. Content authors can share these links with anyone, allowing non-CMS user to view draft page content. Each preview link is valid for 30 days.

## Requirements

- SilverStripe ^3.1

## Installation

```
$ composer require silverstripe/sharedraftcontent
```

You'll also need to run `dev/build`.

## Documentation

See the [docs/en](docs/en/introduction.md) folder.

## Versioning

This library follows [Semver](http://semver.org). According to Semver, you will be able to upgrade to any minor or patch version of this library without any breaking changes to the public API. Semver also requires that we clearly define the public API for this library.

All methods, with `public` visibility, are part of the public API. All other methods are not part of the public API. Where possible, we'll try to keep `protected` methods backwards-compatible in minor/patch versions, but if you're overriding methods then please test your work before upgrading.

## Reporting Issues

Please [create an issue](http://github.com/silverstripe-labs/silverstripe-sharedraftcontent/issues) for any bugs you've found, or features you're missing.


text:
1. Build a Docker image from the Dockerfile
  - Use the Docker QuickStart Terminal
  - `cd` into the app source directory
  - Build the docker image
    + Replace username with your DockerHub account name (or any name)
    + The --file argument is optional
  - After building image, you can view the images
    + `docker images`

    ```
    docker build --tag tonysneed/aspnetcore2 -- file Dockerfile .
    ```

3. Create and run a docker container
  - Use `docker run` to create and start a container
  - Use the `-v` flag to map the current working directory to the app folder

    ```
    docker run -d -p 5000:5000 --name web2 -v $(pwd):/app tonysneed/aspnetcore2
    ```

4. Run the app from a browser
  - Run `docker-machine ip` to reveal the VM's IP address
  - Use the IP address to open the web app
    + `http://192.168.99.100:5000/hello.html`

5. Now with the container still running, edit the file **hello.html** under wwwroot
  - Add "from Docker" to the end of the greeting
  - Simply *refresh the browser* to view the updated text!

## Part B: Monitoring File Changes with Dnx-Watch

1. In this part we've refactored the project to use an MVC controller.
  - Add a dependency for Mvc, call AddMvc and UseMvc in the Startup class
  - This is so that we can use `dnx-watch` to restart the app when changes are detected
  - Add a Home controller with an Index action that returns formatted text
  - Inject IHostingEnvironment to get the environment name

2. Add a Dockerfile which is based on microsoft/aspnet:1.0.0-rc1-update1
  - Note that we must depend on the Mono-based image, rather than on Core CLR,
    in order for dnx-watch to work
  - We need to set some environment variables for location of packages and commands
  - We install the dnx-watch command, which monitors file changes

3. Build the image, then create and run a container based on the image

4. Run the app from a browser
  - Run `docker-machine ip` to reveal the VM's IP address
  - Use the IP address to open the web app
    + `http://192.168.99.100:5000`

5. Now with the container still running, edit the **HomeController** under Controllers
  - Change the text returned from the Index action
  - Then *refresh the browser* to view the updated text!


text:
package mono.android.support.v4.view;

public class ViewPropertyAnimatorListenerImplementor
	extends java.lang.Object
	implements
		mono.android.IGCUserPeer,
		android.support.v4.view.ViewPropertyAnimatorListener
{
	static final String __md_methods;
	static {
		__md_methods =
			"n_onAnimationCancel:(Landroid/view/View;)V:GetOnAnimationCancel_Landroid_view_View_Handler:Android.Support.V4.View.IViewPropertyAnimatorListenerInvoker, Xamarin.Android.Support.v4\n" +
			"n_onAnimationEnd:(Landroid/view/View;)V:GetOnAnimationEnd_Landroid_view_View_Handler:Android.Support.V4.View.IViewPropertyAnimatorListenerInvoker, Xamarin.Android.Support.v4\n" +
			"n_onAnimationStart:(Landroid/view/View;)V:GetOnAnimationStart_Landroid_view_View_Handler:Android.Support.V4.View.IViewPropertyAnimatorListenerInvoker, Xamarin.Android.Support.v4\n" +
			"";
		mono.android.Runtime.register ("Android.Support.V4.View.IViewPropertyAnimatorListenerImplementor, Xamarin.Android.Support.v4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", ViewPropertyAnimatorListenerImplementor.class, __md_methods);
	}

	public ViewPropertyAnimatorListenerImplementor () throws java.lang.Throwable
	{
		super ();
		if (getClass () == ViewPropertyAnimatorListenerImplementor.class)
			mono.android.TypeManager.Activate ("Android.Support.V4.View.IViewPropertyAnimatorListenerImplementor, Xamarin.Android.Support.v4, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null", "", this, new java.lang.Object[] {  });
	}

	public void onAnimationCancel (android.view.View p0)
	{
		n_onAnimationCancel (p0);
	}

	private native void n_onAnimationCancel (android.view.View p0);

	public void onAnimationEnd (android.view.View p0)
	{
		n_onAnimationEnd (p0);
	}

	private native void n_onAnimationEnd (android.view.View p0);

	public void onAnimationStart (android.view.View p0)
	{
		n_onAnimationStart (p0);
	}

	private native void n_onAnimationStart (android.view.View p0);

	java.util.ArrayList refList;
	public void monodroidAddReference (java.lang.Object obj)
	{
		if (refList == null)
			refList = new java.util.ArrayList ();
		refList.add (obj);
	}

	public void monodroidClearReferences ()
	{
		if (refList != null)
			refList.clear ();
	}
}


text:
import { Observable } from 'rxjs/Rx';
import { Subject } from 'rxjs/Subject';
import { ReplaySubject } from 'rxjs/ReplaySubject';

export function normalSubject() {
  const interval$ = Observable.interval(1000).take(7);
  const subject = new Subject();
  subject.map((value) => `Observer one ${value}`).subscribe((value) => {
    console.log(value);
  });
  // interval$.subscribe(subject);
  subject.next('test');

  setTimeout(() => {
    subject.map((value) => `Observer two ${value}`).subscribe((value) => {
      console.log(value);
    });
  }, 2000);

}

export function replaySubject() {
  const subject = new ReplaySubject(3);

  subject.next('one');
  subject.next('two');
  subject.next('three');
  subject.next('four');

  setTimeout(() => {
    subject.map((value) => `Latest Observer ${value}`).subscribe((value) => {
      console.log(value);
    });
    subject.next('five');
  }, 2000);

}


text:
using Innovator.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace InnovatorAdmin.Scripts
{
  [DisplayName("Replace Item")]
  public class ReplaceItem : IAsyncScript
  {
    [DisplayName("Original ID"), Description("The ID of the original item which will be replaced")]
    public string OrigId { get; set; }
    [DisplayName("Replace ID"), Description("The ID of the replacement item with which the original will be replaced")]
    public string ReplaceId { get; set; }
    [DisplayName("Item Type"), Description("The type of the item to replace")]
    public string Type { get; set; }
    [DisplayName("Generate SQL"), Description("Whether to generate the SQL for the replace instead of actually doing the replace")]
    public bool GenerateSql { get; set; }

    public IPromise<string> Execute(IAsyncConnection conn)
    {
      return ExecuteAsync(conn).ToPromise();
    }

    private async Task<string> ExecuteAsync(IAsyncConnection conn)
    {
      var whereUsed = await GetWhereUsed(conn, this.Type, this.OrigId);
      var finalSql = new StringBuilder();
      string sql;
      string props;
      IReadOnlyResult res;
      foreach (var item in whereUsed)
      {
        props = item.Properties.Select(p => p + " = '" + this.ReplaceId + "'").GroupConcat(", ");
        sql = "update innovator.[" + item.MainType.Replace(' ', '_') + "] set " + props + " where id ='" + item.MainId + "';";
        if (this.GenerateSql)
        {
          finalSql.AppendLine(sql);
        }
        else
        {
          res = await conn.ApplySql(sql, true).ToTask();
          res.AssertNoError();
        }
      }

      if (this.GenerateSql)
        return finalSql.ToString();
      return "Complete.";
    }

    private async Task<IEnumerable<WhereUsedItem>> GetWhereUsed(IAsyncConnection conn, string type, string id)
    {
      var whereUsed = await conn.ApplyAsync(@"<AML>
                                                <Item type='SQL' action='SQL Process'>
                                                  <name>WhereUsed_General</name>
                                                  <PROCESS>CALL</PROCESS>
                                                  <ARG1>@0</ARG1>
                                                  <ARG2>@1</ARG2>
                                                </Item>
                                              </AML>", true, false, type, id).ToTask();
      return (
        from i in whereUsed.Items()
        where string.IsNullOrEmpty(type) || i.Property("parent_type").Value == type
        select new WhereUsedItem()
        {
          Type = i.Property("parent_type").Value,
          Id = i.Property("parent_id").Value,
          Icon = i.Property("icon").Value,
          MainType = i.Property("main_type").Value,
          MainId = i.Property("main_id").Value,
          Properties = i.Elements().OfType<IReadOnlyProperty>()
            .Where(p => p.Name.Length == 2 && p.Name[0] == 'p' && char.IsNumber(p.Name[1]))
            .Select(p => p.Value),
          Generation = i.Generation().AsInt(1),
          KeyedName = i.KeyedName().Value,
          MajorRev = i.MajorRev().Value
        }).ToList();
    }

    private class WhereUsedItem
    {
      public string Type { get; set; }
      public string Id { get; set; }
      public string Icon { get; set; }
      public string MainType { get; set; }
      public string MainId { get; set; }
      public IEnumerable<string> Properties { get; set; }
      public int Generation { get; set; }
      public string KeyedName { get; set; }
      public string MajorRev { get; set; }
    }
  }
}


text:
function [nextQuat, nextStates, Tbn, correctedDelAng, correctedDelVel]  = PredictStates( ...
    quat, ... % previous quaternion states 4x1
    states, ... % previous states (3x1 rotation error, 3x1 velocity, 3x1 gyro bias)
    angRate, ... % IMU rate gyro measurements, 3x1 (rad/sec)
    accel, ... % IMU accelerometer measurements 3x1 (m/s/s)
    dt) % time since last IMU measurement (sec)

% Define parameters used for previous angular rates and acceleration shwich
% are used for trapezoidal integration
persistent prevAngRate;
if isempty(prevAngRate)
    prevAngRate = angRate;
end
persistent prevAccel;
if isempty(prevAccel)
    prevAccel = accel;
end
% define persistent variables for previous delta angle and velocity which
% are required for sculling and coning error corrections
persistent prevDelAng;
if isempty(prevDelAng)
    prevDelAng = single([0;0;0]);
end
persistent prevDelVel;
if isempty(prevDelVel)
    prevDelVel = single([0;0;0]);
end

% Convert IMU data to delta angles and velocities using trapezoidal
% integration
dAng = 0.5*(angRate + prevAngRate)*dt;
dVel = 0.5*(accel   + prevAccel  )*dt;
prevAngRate = angRate;
prevAccel   = accel;

% Remove sensor bias errors
dAng = dAng - states(7:9);

% Apply rotational and skulling corrections
correctedDelVel= dVel + ...
    0.5*cross(prevDelAng + dAng , prevDelVel + dVel) + 1/6*cross(prevDelAng + dAng , cross(prevDelAng + dAng , prevDelVel + dVel)) + ... % rotational correction
    1/12*(cross(prevDelAng , dVel) + cross(prevDelVel , dAng)); % sculling correction

% Apply corrections for coning errors
correctedDelAng   = dAng - 1/12*cross(prevDelAng , dAng);

% Save current measurements
prevDelAng = dAng;
prevDelVel = dVel;

% Initialise the updated state vector
nextQuat = quat;
nextStates   = states;

% Convert the rotation vector to its equivalent quaternion
rotationMag = sqrt(correctedDelAng(1)^2 + correctedDelAng(2)^2 + correctedDelAng(3)^2);
if rotationMag<1e-12
  deltaQuat = single([1;0;0;0]);
else
  deltaQuat = [cos(0.5*rotationMag); correctedDelAng/rotationMag*sin(0.5*rotationMag)];
end

% Update the quaternions by rotating from the previous attitude through
% the delta angle rotation quaternion
qUpdated = [quat(1)*deltaQuat(1)-transpose(quat(2:4))*deltaQuat(2:4); quat(1)*deltaQuat(2:4) + deltaQuat(1)*quat(2:4) + cross(quat(2:4),deltaQuat(2:4))];

% Normalise the quaternions and update the quaternion states
quatMag = sqrt(qUpdated(1)^2 + qUpdated(2)^2 + qUpdated(3)^2 + qUpdated(4)^2);
if (quatMag < 1e-16)
    nextQuat(1:4) = qUpdated;
else
    nextQuat(1:4) = qUpdated / quatMag;
end

% Calculate the body to nav cosine matrix
Tbn = Quat2Tbn(nextQuat);

% transform body delta velocities to delta velocities in the nav frame
delVelNav = Tbn * correctedDelVel + [0;0;9.807]*dt;

% Sum delta velocities to get velocity
nextStates(4:6) = states(4:6) + delVelNav(1:3);

end


text:
package reactivestreams.tour;

import com.mongodb.client.result.DeleteResult;
import com.mongodb.client.result.InsertManyResult;
import com.mongodb.client.result.InsertOneResult;
import com.mongodb.client.result.UpdateResult;
import com.mongodb.reactivestreams.client.MongoClient;
import com.mongodb.reactivestreams.client.MongoClients;
import com.mongodb.reactivestreams.client.MongoCollection;
import com.mongodb.reactivestreams.client.MongoDatabase;
import org.bson.Document;
import reactivestreams.helpers.SubscriberHelpers.ObservableSubscriber;
import reactivestreams.helpers.SubscriberHelpers.OperationSubscriber;
import reactivestreams.helpers.SubscriberHelpers.PrintDocumentSubscriber;
import reactivestreams.helpers.SubscriberHelpers.PrintSubscriber;

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

import static com.mongodb.client.model.Accumulators.sum;
import static com.mongodb.client.model.Aggregates.group;
import static com.mongodb.client.model.Aggregates.match;
import static com.mongodb.client.model.Aggregates.project;
import static com.mongodb.client.model.Filters.and;
import static com.mongodb.client.model.Filters.eq;
import static com.mongodb.client.model.Filters.exists;
import static com.mongodb.client.model.Filters.gt;
import static com.mongodb.client.model.Filters.gte;
import static com.mongodb.client.model.Filters.lt;
import static com.mongodb.client.model.Filters.lte;
import static com.mongodb.client.model.Projections.excludeId;
import static com.mongodb.client.model.Sorts.descending;
import static com.mongodb.client.model.Updates.inc;
import static com.mongodb.client.model.Updates.set;
import static java.util.Arrays.asList;
import static java.util.Collections.singletonList;

/**
 * The QuickTour code example
 */
public class QuickTour {
    /**
     * Run this main method to see the output of this quick example.
     *
     * @param args takes an optional single argument for the connection string
     */
    public static void main(final String[] args) {
        MongoClient mongoClient;

        if (args.length == 0) {
            // connect to the local database server
            mongoClient = MongoClients.create();
        } else {
            mongoClient = MongoClients.create(args[0]);
        }

        // get handle to "mydb" database
        MongoDatabase database = mongoClient.getDatabase("mydb");

        // get a handle to the "test" collection
        MongoCollection<Document> collection = database.getCollection("test");

        // drop all the data in it
        ObservableSubscriber<Void> successSubscriber = new OperationSubscriber<>();
        collection.drop().subscribe(successSubscriber);
        successSubscriber.await();

        // make a document and insert it
        Document doc = new Document("name", "MongoDB")
                .append("type", "database")
                .append("count", 1)
                .append("info", new Document("x", 203).append("y", 102));

        ObservableSubscriber<InsertOneResult> insertOneSubscriber = new OperationSubscriber<>();
        collection.insertOne(doc).subscribe(insertOneSubscriber);
        insertOneSubscriber.await();

        // get it (since it's the only one in there since we dropped the rest earlier on)
        ObservableSubscriber<Document> documentSubscriber = new PrintDocumentSubscriber();
        collection.find().first().subscribe(documentSubscriber);
        documentSubscriber.await();

        // now, lets add lots of little documents to the collection so we can explore queries and cursors
        List<Document> documents = new ArrayList<>();
        for (int i = 0; i < 100; i++) {
            documents.add(new Document("i", i));
        }

        ObservableSubscriber<InsertManyResult> insertManySubscriber = new OperationSubscriber<>();
        collection.insertMany(documents).subscribe(insertManySubscriber);
        insertManySubscriber.await();

        // find first
        documentSubscriber = new PrintDocumentSubscriber();
        collection.find().first().subscribe(documentSubscriber);
        documentSubscriber.await();

        // lets get all the documents in the collection and print them out
        documentSubscriber = new PrintDocumentSubscriber();
        collection.find().subscribe(documentSubscriber);
        documentSubscriber.await();

        // Query Filters

        // now use a query to get 1 document out
        documentSubscriber = new PrintDocumentSubscriber();
        collection.find(eq("i", 71)).first().subscribe(documentSubscriber);
        documentSubscriber.await();

        // now use a range query to get a larger subset
        documentSubscriber = new PrintDocumentSubscriber();
        collection.find(gt("i", 50)).subscribe(documentSubscriber);
        documentSubscriber.await();

        // range query with multiple constraints
        documentSubscriber = new PrintDocumentSubscriber();
        collection.find(and(gt("i", 50), lte("i", 100))).subscribe(documentSubscriber);
        documentSubscriber.await();

        // Sorting
        documentSubscriber = new PrintDocumentSubscriber();
        collection.find(exists("i")).sort(descending("i")).first().subscribe(documentSubscriber);
        documentSubscriber.await();

        // Projection
        documentSubscriber = new PrintDocumentSubscriber();
        collection.find().projection(excludeId()).first().subscribe(documentSubscriber);
        documentSubscriber.await();

        // Aggregation
        documentSubscriber = new PrintDocumentSubscriber();
        collection.aggregate(asList(
                match(gt("i", 0)),
                project(Document.parse("{ITimes10: {$multiply: ['$i', 10]}}")))
        ).subscribe(documentSubscriber);
        documentSubscriber.await();

        documentSubscriber = new PrintDocumentSubscriber();
        collection.aggregate(singletonList(group(null, sum("total", "$i"))))
                .first().subscribe(documentSubscriber);
        documentSubscriber.await();

        // Update One
        ObservableSubscriber<UpdateResult> updateSubscriber = new OperationSubscriber<>();
        collection.updateOne(eq("i", 10), set("i", 110)).subscribe(updateSubscriber);
        updateSubscriber.await();

        // Update Many
        updateSubscriber = new OperationSubscriber<>();
        collection.updateMany(lt("i", 100), inc("i", 100)).subscribe(updateSubscriber);
        updateSubscriber.await();

        // Delete One
        ObservableSubscriber<DeleteResult> deleteSubscriber = new OperationSubscriber<>();
        collection.deleteOne(eq("i", 110)).subscribe(deleteSubscriber);
        deleteSubscriber.await();

        // Delete Many
        deleteSubscriber = new OperationSubscriber<>();
        collection.deleteMany(gte("i", 100)).subscribe(deleteSubscriber);
        deleteSubscriber.await();

        // Create Index
        OperationSubscriber<String> createIndexSubscriber = new PrintSubscriber<>("Create Index Result: %s");
        collection.createIndex(new Document("i", 1)).subscribe(createIndexSubscriber);
        createIndexSubscriber.await();

        // Clean up
        successSubscriber = new OperationSubscriber<>();
        collection.drop().subscribe(successSubscriber);
        successSubscriber.await();

        // release resources
        mongoClient.close();
    }
}


text:
package com.deleidos.rtws.jmx.management.system;

import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

import org.hyperic.sigar.CpuInfo;
import org.hyperic.sigar.CpuPerc;
import org.hyperic.sigar.FileSystem;
import org.hyperic.sigar.FileSystemUsage;
import org.hyperic.sigar.Mem;
import org.hyperic.sigar.NetStat;
import org.hyperic.sigar.ProcStat;
import org.hyperic.sigar.Sigar;
import org.hyperic.sigar.SigarException;
import org.hyperic.sigar.Swap;
import org.hyperic.sigar.Tcp;

import com.deleidos.rtws.commons.management.OSMetricsMXBean;
import com.deleidos.rtws.commons.model.jmx.FileSystemStatBean;

public class OSMetricsManagedBean implements OSMetricsMXBean {

	/** The object that stores the system metrics */
	private Sigar sigar;

	public OSMetricsManagedBean() {
		this.sigar = new Sigar();
	}

	public double getUptime() throws SigarException {
		return this.sigar.getUptime().getUptime();
	}

	public double [] getLoadAverage() throws SigarException {
		// load average in 1 min, 5 min, and 15 min interval
		return this.sigar.getLoadAverage();
	}

	public CpuInfo getCpuInfo() throws SigarException {
		return (this.sigar.getCpuInfoList())[0];
	}

	public CpuPerc [] getCpuPercStat() throws SigarException {
		return this.sigar.getCpuPercList();
	}

	public ProcStat getProcStat() throws SigarException {
		return this.sigar.getProcStat();
	}

	public Mem getMemStat() throws SigarException {
		return this.sigar.getMem();
	}

	public Swap getSwapStat() throws SigarException {
		return this.sigar.getSwap();
	}

	public List<FileSystemStatBean> getFileSystemStat() throws SigarException {
		List<FileSystemStatBean> fsStatList = new LinkedList<FileSystemStatBean>();

		FileSystem [] fsList = this.sigar.getFileSystemList();
		for (FileSystem fs : fsList) {
			FileSystemUsage fsUsage = sigar.getFileSystemUsage(fs.getDirName());

			FileSystemStatBean fsStat = new FileSystemStatBean(fs.getDevName(), fs.getDirName(),
					fs.getSysTypeName(), fs.getTypeName(), fsUsage.getDiskReads(), fsUsage.getDiskReadBytes(),
					fsUsage.getDiskWrites(), fsUsage.getDiskWriteBytes());

			fsStatList.add(fsStat);
		}

		return fsStatList;
	}

	public NetStat getNetStat() throws SigarException {
		return this.sigar.getNetStat();
	}

	public Tcp getTcpStat() throws SigarException {
		return this.sigar.getTcp();
	}

	public void buildObjectNameKeys(Properties keys) {
		keys.put("type", "OSMetrics");
	}

}


text:
package rfs // import "github.com/garthk/nag/pkg/readable-fs"

import (
	"bytes"
	"os"
)

type FakeReadableFile struct {
	basename string
	bytes    []byte
	members  []*FakeReadableFile
	mode     os.FileMode
}

func (f FakeReadableFile) Name() string {
	return f.basename
}

func (f FakeReadableFile) Size() int64 {
	return int64(len(f.bytes))
}

func (f FakeReadableFile) Mode() os.FileMode {
	return f.mode
}

func FromString(str string) []byte {
	return bytes.NewBufferString(str).Bytes()
}


text:
import createPolymorphFunction from '../../../util/createPolymorphFunction/index.js';
import $get from '../get/index.js';

//
// Counts values in objects, arrays or strings
//
export default createPolymorphFunction(
    path => subject => {
        const object = $get(path, subject);

        if (!object) {
            return 0;
        }

        if (typeof object.count === 'function') {
            return object.count();
        }

        if (Array.isArray(object) || typeof object === 'string') {
            return object.length;
        }

        if (typeof object === 'object') {
            return Object.keys(object).length;
        }

        return 0;
    }
);


text:
package org.apache.activemq.perf;

/**
 *
 */
public class PerfRate {

   protected int totalCount;
   protected int count;
   protected long startTime = System.currentTimeMillis();

   /**
    * @return Returns the count.
    */
   public int getCount() {
      return totalCount;
   }

   public synchronized void increment() {
      totalCount++;
      count++;
   }

   public int getRate() {
      long endTime = System.currentTimeMillis();
      long totalTime = endTime - startTime;
      int result = (int) ((count * 1000) / totalTime);
      return result;
   }

   /**
    * Resets the rate sampling.
    */
   public synchronized PerfRate cloneAndReset() {
      PerfRate rc = new PerfRate();
      rc.totalCount = totalCount;
      rc.count = count;
      rc.startTime = startTime;
      count = 0;
      startTime = System.currentTimeMillis();
      return rc;
   }

   /**
    * Resets the rate sampling.
    */
   public void reset() {
      count = 0;
      startTime = System.currentTimeMillis();
   }

   /**
    * @return Returns the totalCount.
    */
   public int getTotalCount() {
      return totalCount;
   }

   /**
    * @param totalCount The totalCount to set.
    */
   public void setTotalCount(int totalCount) {
      this.totalCount = totalCount;
   }
}


text:
package com.facebook.buck.cli;

import com.facebook.buck.event.ConsoleEvent;
import com.facebook.buck.parser.PerBuildState;
import com.facebook.buck.parser.SpeculativeParsing;
import com.facebook.buck.util.MoreExceptions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;

import org.kohsuke.args4j.Argument;
import org.kohsuke.args4j.Option;

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

public class AuditDependenciesCommand extends AbstractCommand {

  @Option(name = "--json",
      usage = "Output in JSON format")
  private boolean generateJsonOutput;

  public boolean shouldGenerateJsonOutput() {
    return generateJsonOutput;
  }

  @Option(
      name = "--include-tests",
      usage = "Includes a target's tests with its dependencies. With the transitive flag, this " +
          "prints the dependencies of the tests as well")
  private boolean includeTests = false;

  @Option(name = "--transitive",
      aliases = { "-t" },
      usage = "Whether to include transitive dependencies in the output")
  private boolean transitive = false;

  @Argument
  private List<String> arguments = new ArrayList<>();

  public List<String> getArguments() {
    return arguments;
  }

  public boolean shouldShowTransitiveDependencies() {
    return transitive;
  }

  public boolean shouldIncludeTests() {
    return includeTests;
  }

  public ImmutableList<String> getArgumentsFormattedAsBuildTargets(BuckConfig buckConfig) {
    return getCommandLineBuildTargetNormalizer(buckConfig).normalizeAll(getArguments());
  }

  @Override
  public int runWithoutHelp(final CommandRunnerParams params)
      throws IOException, InterruptedException {
    final ImmutableSet<String> fullyQualifiedBuildTargets = ImmutableSet.copyOf(
        getArgumentsFormattedAsBuildTargets(params.getBuckConfig()));

    if (fullyQualifiedBuildTargets.isEmpty()) {
      params.getBuckEventBus().post(ConsoleEvent.severe(
          "Must specify at least one build target."));
      return 1;
    }

    if (params.getConsole().getAnsi().isAnsiTerminal()) {
      params.getBuckEventBus().post(ConsoleEvent.info(
          "'buck audit dependencies' is deprecated. Please use 'buck query' instead.\n" +
          "The equivalent 'buck query' command is:\n$ %s\n\nThe query language is documented at " +
          "https://buckbuild.com/command/query.html",
          QueryCommand.buildAuditDependenciesQueryExpression(
              getArguments(),
              shouldShowTransitiveDependencies(),
              shouldIncludeTests(),
              shouldGenerateJsonOutput())));
    }

    try (CommandThreadManager pool =
             new CommandThreadManager("Audit", getConcurrencyLimit(params.getBuckConfig()));
         PerBuildState parserState =
             new PerBuildState(
                 params.getParser(),
                 params.getBuckEventBus(),
                 pool.getExecutor(),
                 params.getCell(),
                 getEnableParserProfiling(),
                 SpeculativeParsing.of(true),
                 /* ignoreBuckAutodepsFiles */ false)) {
      BuckQueryEnvironment env =
          BuckQueryEnvironment.from(params, parserState, getEnableParserProfiling());
      return QueryCommand.runMultipleQuery(
          params,
          env,
          pool.getExecutor(),
          QueryCommand.getAuditDependenciesQueryFormat(
              shouldShowTransitiveDependencies(),
              shouldIncludeTests()),
          getArgumentsFormattedAsBuildTargets(params.getBuckConfig()),
          shouldGenerateJsonOutput());
    } catch (Exception e) {
      if (e.getCause() instanceof InterruptedException) {
        throw (InterruptedException) e.getCause();
      }
      params.getBuckEventBus().post(ConsoleEvent.severe(
          MoreExceptions.getHumanReadableOrLocalizedMessage(e)));
      return 1;
    }
  }

  @Override
  public boolean isReadOnly() {
    return true;
  }

  @Override
  public String getShortDescription() {
    return "provides facilities to audit build targets' dependencies";
  }

}


text:
package com.expedia.seiso.security;

import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.SortedSet;

import javax.naming.NamingEnumeration;
import javax.naming.directory.Attributes;

import lombok.extern.slf4j.XSlf4j;

import org.springframework.ldap.core.DirContextAdapter;
import org.springframework.ldap.core.DirContextOperations;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.ldap.userdetails.UserDetailsContextMapper;
import org.springframework.stereotype.Component;

/**
 * Maps Active Directory user to Seiso user. This might work for LDAP servers generally as well. I'm not sure.
 *
 * @author Willie Wheeler
 */
@Component
@XSlf4j
public class SeisoUserDetailsContextMapper implements UserDetailsContextMapper {

	// TODO Inject role/permission mapping and use it to add permissions

	private static final String AD_GIVEN_NAME = "givenname";
	private static final String AD_SURNAME = "sn";
	private static final String AD_EMAIL = "mail";

	@Override
	public UserDetails mapUserFromContext(
			DirContextOperations ctx,
			String username,
			Collection<? extends GrantedAuthority> authorities) {

//		printAttributeIds(ctx);

		SeisoUser user = new SeisoUser(username, mapAuthorities(authorities));
		user.setFirstName(extractUnique(ctx, AD_GIVEN_NAME));
		user.setLastName(extractUnique(ctx, AD_SURNAME));
		user.setEmail(extractUnique(ctx, AD_EMAIL));

		// FIXME Figure out how we want to handle these
		user.setEnabled(true);
		user.setAccountNonExpired(true);
		user.setAccountNonLocked(true);
		user.setCredentialsNonExpired(true);

		return user;
	}

	@Override
	public void mapUserToContext(UserDetails user, DirContextAdapter ctx) {
		// Not relevant for authentication:
		// http://docs.spring.io/spring-security/site/docs/current/reference/htmlsingle/#ldap-custom-user-details
		throw new UnsupportedOperationException("Not supported");
	}

	@SuppressWarnings("unused")
	private void printAttributeIds(DirContextOperations ctx) {
		Attributes attrs = ctx.getAttributes();
		NamingEnumeration<? extends String> allAttrs = attrs.getIDs();
		while (allAttrs.hasMoreElements()) {
			String attrId = allAttrs.nextElement();
			log.trace("attrId={}", attrId);
		}
	}

	private Collection<? extends GrantedAuthority> mapAuthorities(Collection<? extends GrantedAuthority> authorities) {

		// TODO Handle administrative users.
		// Fine to hardcode as "Seiso Admin" -> Roles.ADMIN for now.
		Set<GrantedAuthority> mapped = new HashSet<>();
		// Auto-prepend ROLE_ since the framework expects this.
		mapped.add(new SimpleGrantedAuthority("ROLE_" + Roles.USER));
		return mapped;
	}

	private String extractUnique(DirContextOperations ctx, String name) {
		SortedSet<String> mailSet = ctx.getAttributeSortedStringSet(name);
		Iterator<String> it = mailSet.iterator();
		return it.hasNext() ? it.next() : null;
	}
}