text:
'use strict';

var d3 = require('d3');
var isNumeric = require('fast-isnumeric');

var Plotly = require('../../plotly');
var Plots = require('../../plots/plots');
var Lib = require('../../lib');
var Drawing = require('../drawing');
var Color = require('../color');
var svgTextUtils = require('../../lib/svg_text_utils');
var interactConstants = require('../../constants/interactions');

var Titles = module.exports = {};

var numStripRE = / [XY][0-9]* /;

/**
 * Titles - (re)draw titles on the axes and plot:
 * @param {DOM element} gd - the graphDiv
 * @param {string} titleClass - the css class of this title
 * @param {object} options - how and what to draw
 *      propContainer - the layout object containing `title` and `titlefont`
 *          attributes that apply to this title
 *      propName - the full name of the title property (for Plotly.relayout)
 *      [traceIndex] - include only if this property applies to one trace
 *          (such as a colorbar title) - then editing pipes to Plotly.restyle
 *          instead of Plotly.relayout
 *      placeholder - placeholder text for an empty editable title
 *      [avoid] {object} - include if this title should move to avoid other elements
 *          selection - d3 selection of elements to avoid
 *          side - which direction to move if there is a conflict
 *          [offsetLeft] - if these elements are subject to a translation
 *              wrt the title element
 *          [offsetTop]
 *      attributes {object} - position and alignment attributes
 *          x - pixels
 *          y - pixels
 *          text-anchor - start|middle|end
 *      transform {object} - how to transform the title after positioning
 *          rotate - degrees
 *          offset - shift up/down in the rotated frame (unused?)
 *      containerGroup - if an svg <g> element already exists to hold this
 *          title, include here. Otherwise it will go in fullLayout._infolayer
 *
 *  @return {selection} d3 selection of title container group
 */
Titles.draw = function(gd, titleClass, options) {
    var cont = options.propContainer;
    var prop = options.propName;
    var placeholder = options.placeholder;
    var traceIndex = options.traceIndex;
    var avoid = options.avoid || {};
    var attributes = options.attributes;
    var transform = options.transform;
    var group = options.containerGroup;

    var fullLayout = gd._fullLayout;
    var titlefont = cont.titlefont || {};
    var font = titlefont.family;
    var fontSize = titlefont.size;
    var fontColor = titlefont.color;

    var opacity = 1;
    var isplaceholder = false;
    var txt = (cont.title || '').trim();

    // only make this title editable if we positively identify its property
    // as one that has editing enabled.
    var editAttr;
    if(prop === 'title') editAttr = 'titleText';
    else if(prop.indexOf('axis') !== -1) editAttr = 'axisTitleText';
    else if(prop.indexOf('colorbar' !== -1)) editAttr = 'colorbarTitleText';
    var editable = gd._context.edits[editAttr];
    // ion: selective title editing hack	if (editable) {
        if (cont === fullLayout) {
            // MAIN TITLE
            editable = gd._context.editableMainTitle;
        } else if (cont === fullLayout.xaxis) {
            editable = gd._context.editableAxisXTitle;
        } else if (cont === fullLayout.yaxis) {
            editable = gd._context.editableAxisYTitle;
        } else if (cont === fullLayout.yaxis2) {
            editable = gd._context.editableAxisY2Title;
        } else if (cont === fullLayout.xaxis2) {
            editable = gd._context.editableAxisX2Title;
        }
    //}
    if(txt === '') opacity = 0;
    // look for placeholder text while stripping out numbers from eg X2, Y3
    // this is just for backward compatibility with the old version that had
    // "Click to enter X2 title" and may have gotten saved in some old plots,
    // we don't want this to show up when these are displayed.
    else if(txt.replace(numStripRE, ' % ') === placeholder.replace(numStripRE, ' % ')) {
        opacity = 0.2;
        isplaceholder = true;
        if(!editable) txt = '';
    }

    var elShouldExist = txt || editable;

    if(!group) {
        group = fullLayout._infolayer.selectAll('.g-' + titleClass)
            .data([0]);
        group.enter().append('g')
            .classed('g-' + titleClass, true);
    }

    var el = group.selectAll('text')
        .data(elShouldExist ? [0] : []);
    el.enter().append('text');
    el.text(txt)
        // this is hacky, but convertToTspans uses the class
        // to determine whether to rotate mathJax...
        // so we need to clear out any old class and put the
        // correct one (only relevant for colorbars, at least
        // for now) - ie don't use .classed
        .attr('class', titleClass);
    el.exit().remove();

    if(!elShouldExist) return group;

    function titleLayout(titleEl) {
        Lib.syncOrAsync([drawTitle, scootTitle], titleEl);
    }

    function drawTitle(titleEl) {
        var transformVal;

        if(transform) {
            transformVal = '';
            if(transform.rotate) {
                transformVal += 'rotate(' + [transform.rotate, attributes.x, attributes.y] + ')';
            }
            if(transform.offset) {
                transformVal += 'translate(0, ' + transform.offset + ')';
            }
        } else {
            transformVal = null;
        }

        titleEl.attr('transform', transformVal);

        titleEl.style({
            'font-family': font,
            'font-size': d3.round(fontSize, 2) + 'px',
            fill: Color.rgb(fontColor),
            opacity: opacity * Color.opacity(fontColor),
            'font-weight': Plots.fontWeight
        })
        .attr(attributes)
        .call(svgTextUtils.convertToTspans, gd);

        return Plots.previousPromises(gd);
    }

    function scootTitle(titleElIn) {
        var titleGroup = d3.select(titleElIn.node().parentNode);

        if(avoid && avoid.selection && avoid.side && txt) {
            titleGroup.attr('transform', null);

            // move toward avoid.side (= left, right, top, bottom) if needed
            // can include pad (pixels, default 2)
            var shift = 0;
            var backside = {
                left: 'right',
                right: 'left',
                top: 'bottom',
                bottom: 'top'
            }[avoid.side];
            var shiftSign = (['left', 'top'].indexOf(avoid.side) !== -1) ?
                    -1 : 1;
            var pad = isNumeric(avoid.pad) ? avoid.pad : 2;
            var titlebb = Drawing.bBox(titleGroup.node());
            var paperbb = {
                left: 0,
                top: 0,
                right: fullLayout.width,
                bottom: fullLayout.height
            };
            var maxshift = avoid.maxShift || (
                (paperbb[avoid.side] - titlebb[avoid.side]) *
                ((avoid.side === 'left' || avoid.side === 'top') ? -1 : 1));
            // Prevent the title going off the paper
            if(maxshift < 0) shift = maxshift;
            else {
                // so we don't have to offset each avoided element,
                // give the title the opposite offset
                var offsetLeft = avoid.offsetLeft || 0;
                var offsetTop = avoid.offsetTop || 0;
                titlebb.left -= offsetLeft;
                titlebb.right -= offsetLeft;
                titlebb.top -= offsetTop;
                titlebb.bottom -= offsetTop;

                // iterate over a set of elements (avoid.selection)
                // to avoid collisions with
                avoid.selection.each(function() {
                    var avoidbb = Drawing.bBox(this);

                    if(Lib.bBoxIntersect(titlebb, avoidbb, pad)) {
                        shift = Math.max(shift, shiftSign * (
                            avoidbb[avoid.side] - titlebb[backside]) + pad);
                    }
                });
                shift = Math.min(maxshift, shift);
            }
            if(shift > 0 || maxshift < 0) {
                var shiftTemplate = {
                    left: [-shift, 0],
                    right: [shift, 0],
                    top: [0, -shift],
                    bottom: [0, shift]
                }[avoid.side];
                titleGroup.attr('transform',
                    'translate(' + shiftTemplate + ')');
            }
        }
    }

    el.call(titleLayout);

    function setPlaceholder() {
        opacity = 0;
        isplaceholder = true;
        el.text(placeholder)
            .on('mouseover.opacity', function() {
                d3.select(this).transition()
                    .duration(interactConstants.SHOW_PLACEHOLDER).style('opacity', 1);
            })
            .on('mouseout.opacity', function() {
                d3.select(this).transition()
                    .duration(interactConstants.HIDE_PLACEHOLDER).style('opacity', 0);
            });
    }

    if(editable) {
        if(!txt) setPlaceholder();
        else el.on('.opacity', null);

        el.call(svgTextUtils.makeEditable, {gd: gd})
            .on('edit', function(text) {
                if(traceIndex !== undefined) Plotly.restyle(gd, prop, text, traceIndex);
                else Plotly.relayout(gd, prop, text);
            })
            .on('cancel', function() {
                this.text(this.attr('data-unformatted'))
                    .call(titleLayout);
            })
            .on('input', function(d) {
                this.text(d || ' ')
                    .call(svgTextUtils.positionText, attributes.x, attributes.y);
            });
    }
    el.classed('js-placeholder', isplaceholder);
	// ion: storing the title element inside its containing axis object
    cont._titleElement = el;
 	return group;};


text:
[Home](./index.md) > [puppeteer](./puppeteer.md) > [Page](./puppeteer.page.md) > [select](./puppeteer.page.select.md)

## Page.select() method

Signature:

```typescript
select(selector: string, ...values: string[]): Promise<string[]>;
```

## Parameters

|  Parameter | Type | Description |
|  --- | --- | --- |
|  selector | string |  |
|  values | string\[\] |  |

Returns:

Promise<string\[\]>

redpajama_set_name: RedPajamaGithub


text:
package com.manage.kernel.jpa.repository;

import com.manage.base.database.enums.TopicStatus;
import java.io.Serializable;
import com.manage.kernel.jpa.entity.NewsTopic;
import java.util.List;
import org.springframework.data.jpa.repository.JpaSpecificationExecutor;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.CrudRepository;
import org.springframework.data.repository.query.Param;

public interface NewsTopicRepo extends CrudRepository<NewsTopic, Serializable>, JpaSpecificationExecutor<NewsTopic> {

    @Query("from NewsTopic where level = 1")
    public List<NewsTopic> queryAllRootTopics();

    @Query("from NewsTopic where code = :code and parentCode = :parentCode")
    public NewsTopic findTopicsByCode(@Param("code") Integer code, @Param("parentCode") Integer parentCode);

}


text:
<?php
/**
 * ConductorTest.php
 *
 * Creation date: 2014-09-24
 * Creation time: 21:05
 *
 * @author Arkadiusz Moskwa <a.moskwa@gmail.com>
 */

namespace Nakard\MusicFormats\Tests\Media\Id3v2\Frame\TextInformation\InvolvedPersons;

use Nakard\MusicFormats\Tests\Media\Id3v2\Frame\TextInformation\AbstractFrameTestCase;
use Nakard\MusicFormats\Media\Id3v2\Frame\TextInformation\InvolvedPersons\Conductor;

/**
 * Class ConductorTest
 *
 * @package Nakard\MusicFormats\Tests\Media\Id3v2\Frame\TextInformation\InvolvedPersons
 */
class ConductorTest extends AbstractFrameTestCase
{
    /**
     * @var Conductor
     */
    protected $frame;

    protected function setUp()
    {
        parent::setUp();
        $this->frame = new Conductor();
    }

    public function testGetIdentifier()
    {
        $this->assertSame('TPE3', $this->frame->getIdentifier());
    }
}


text:
package com.amazonaws.services.transfer.model;

import javax.annotation.Generated;

/**
 *
 */
@Generated("com.amazonaws:aws-java-sdk-code-generator")
public enum SigningAlg {

    SHA256("SHA256"),
    SHA384("SHA384"),
    SHA512("SHA512"),
    SHA1("SHA1"),
    NONE("NONE");

    private String value;

    private SigningAlg(String value) {
        this.value = value;
    }

    @Override
    public String toString() {
        return this.value;
    }

    /**
     * Use this in place of valueOf.
     *
     * @param value
     *        real value
     * @return SigningAlg corresponding to the value
     *
     * @throws IllegalArgumentException
     *         If the specified value does not map to one of the known values in this enum.
     */
    public static SigningAlg fromValue(String value) {
        if (value == null || "".equals(value)) {
            throw new IllegalArgumentException("Value cannot be null or empty!");
        }

        for (SigningAlg enumEntry : SigningAlg.values()) {
            if (enumEntry.toString().equals(value)) {
                return enumEntry;
            }
        }

        throw new IllegalArgumentException("Cannot create enum from " + value + " value!");
    }
}


text:
package org.xenei.jdbc4sparql.sparql.builders;

import java.sql.DatabaseMetaData;
import java.sql.Types;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Set;

import org.xenei.jdbc4sparql.iface.TypeConverter;
import org.xenei.jdbc4sparql.impl.rdf.RdfCatalog;
import org.xenei.jdbc4sparql.impl.rdf.RdfColumnDef;
import org.xenei.jdbc4sparql.impl.rdf.RdfKey;
import org.xenei.jdbc4sparql.impl.rdf.RdfKeySegment;
import org.xenei.jdbc4sparql.impl.rdf.RdfSchema;
import org.xenei.jdbc4sparql.impl.rdf.RdfTable;
import org.xenei.jdbc4sparql.impl.rdf.RdfTableDef;

import com.hp.hpl.jena.query.QuerySolution;
import com.hp.hpl.jena.rdf.model.Model;
import com.hp.hpl.jena.rdf.model.RDFNode;
import com.hp.hpl.jena.rdf.model.Resource;
import com.hp.hpl.jena.util.iterator.Filter;
import com.hp.hpl.jena.util.iterator.Map1;
import com.hp.hpl.jena.util.iterator.WrappedIterator;

/**
 * A simple builder that builds tables for all subjects of [?x a rdfs:Class]
 * triples. Columns for the tables are created from all predicates of all
 * instances of the class.
 */
public class SimpleNormalizingBuilder extends SimpleBuilder {
	public static final String BUILDER_NAME = "Smpl_Norm_Builder";
	public static final String DESCRIPTION = "A simple normalizing schema builder that builds tables based on RDFS Class names";

	// Params: namespace.
	protected static final String TABLE_QUERY = " prefix rdfs: <http://www.w3.org/2000/01/rdf-schema#>"
			+ " SELECT ?tName WHERE { ?tName a rdfs:Class . }";

	// Params: class resource, namespace
	protected static final String COLUMN_QUERY = "SELECT DISTINCT ?cName "
			+ " WHERE { ?instance a <%s> ; ?cName [] ; }";

	private static final String TABLE_SEGMENT = "%1$s <http://www.w3.org/1999/02/22-rdf-syntax-ns#type> <%2$s> .";
	protected static final String COLUMN_SEGMENT = "%1$s <%3$s> %2$s .";
	protected static final String ID_COLUMN_SEGMENT = "BIND( %1$s as %2$s)";

	public RdfColumnDef idColumnDef;

	public SimpleNormalizingBuilder() {
	}

	protected Map<String, String> addColumnDefs(final Set<RdfTable> tableSet,
			final RdfCatalog catalog, final RdfSchema schema,
			final RdfTableDef.Builder tableDefBuilder, final Resource tName,
			final String tableQuerySegment) {
		final Model model = catalog.getResource().getModel();
		final Map<String, String> colNames = new LinkedHashMap<String, String>();
		final List<QuerySolution> solns = catalog.executeQuery(String.format(
				SimpleNormalizingBuilder.COLUMN_QUERY, tName));

		colNames.put("id", SimpleNormalizingBuilder.ID_COLUMN_SEGMENT);

		tableDefBuilder.addColumnDef(idColumnDef);

		for (final QuerySolution soln : solns) {
			final RdfColumnDef.Builder builder = new RdfColumnDef.Builder();
			final Resource cName = soln.getResource("cName");
			final String columnQuerySegment = String.format(
					SimpleNormalizingBuilder.COLUMN_SEGMENT, "%1$s", "%2$s",
					cName.getURI());

			if (multipleCardinality(catalog, tableQuerySegment,
					columnQuerySegment)) {
				tableSet.add(makeSubTable(catalog, schema, tableQuerySegment,
						columnQuerySegment, tName, cName));
			}
			else {
				// might be a duplicate name
				if (colNames.containsKey(cName.getLocalName())) {
					int i = 2;
					while (colNames.containsKey(cName.getLocalName() + i)) {
						i++;
					}
					colNames.put(cName.getLocalName() + i, columnQuerySegment);
				}
				else {
					colNames.put(cName.getLocalName(), columnQuerySegment);
				}
				final int scale = calculateSize(catalog, tableQuerySegment,
						columnQuerySegment);
				builder.setType(Types.VARCHAR)
				.setNullable(DatabaseMetaData.columnNullable)
				.setScale(scale).setReadOnly(true);
				tableDefBuilder.addColumnDef(builder.build(model));
			}
		}
		return colNames;
	}

	private void buildTable(final Set<RdfTable> tableSet,
			final RdfCatalog catalog, final RdfSchema schema,
			final Resource tName) {
		final Model model = schema.getResource().getModel();
		final RdfTableDef.Builder builder = new RdfTableDef.Builder();
		final String tableQuerySegment = String.format(
				SimpleNormalizingBuilder.TABLE_SEGMENT, "%1$s", tName.getURI());
		final Map<String, String> colNames = addColumnDefs(tableSet, catalog,
				schema, builder, tName, tableQuerySegment);

		if (colNames.size() > 1) {
			// add the key segments
			final RdfKeySegment.Builder keySegBuilder = new RdfKeySegment.Builder();
			keySegBuilder.setAscending(true);
			keySegBuilder.setIdx(0);

			final RdfKey.Builder keyBldr = new RdfKey.Builder();
			keyBldr.setUnique(true);
			keyBldr.addSegment(keySegBuilder.build(model));

			builder.setPrimaryKey(keyBldr.build(model));

			// build the def
			final RdfTableDef tableDef = builder.build(model);

			// build the table
			final RdfTable.Builder tblBuilder = new RdfTable.Builder()
			.setTableDef(tableDef)
			.addQuerySegment(tableQuerySegment)
			.setName(tName.getLocalName())
			.setSchema(schema)
			.setRemarks(
					"created by "
							+ SimpleNormalizingBuilder.BUILDER_NAME);

			if (colNames.keySet().size() != tableDef.getColumnCount()) {
				throw new IllegalArgumentException(String.format(
						"There must be %s column names, %s provided",
						tableDef.getColumnCount(), colNames.keySet().size()));
			}

			// set the columns
			final Iterator<String> iter = colNames.keySet().iterator();
			int i = 0;
			while (iter.hasNext()) {

				final String cName = iter.next();
				tblBuilder
				.setColumn(i, cName)
				.getColumn(i)
				.addQuerySegment(colNames.get(cName))
				.setRemarks(
						"created by "
								+ SimpleNormalizingBuilder.BUILDER_NAME);
				i++;
			}

			tableSet.add(tblBuilder.build(model));
		}

	}

	@Override
	protected int calculateSize(final RdfCatalog catalog, final String tableQS,
			final String columnQS) {
		final String queryStr = String.format(
				"SELECT distinct ?col WHERE { %s %s }",
				String.format(tableQS, "?tbl"),
				String.format(columnQS, "?tbl", "?col"));
		final List<QuerySolution> results = catalog.executeQuery(queryStr);

		final Iterator<Integer> iter = WrappedIterator.create(
				results.iterator()).mapWith(new Map1<QuerySolution, Integer>() {

					@Override
					public Integer map1(final QuerySolution o) {
						final RDFNode node = o.get("col");
						if (node == null) {
							return 0;
						}
						if (node.isLiteral()) {
							return TypeConverter.getJavaValue(node.asLiteral())
									.toString().length();
						}
						return node.toString().length();
					}
				});
		int retval = 0;
		while (iter.hasNext()) {
			final Integer i = iter.next();
			if (retval < i) {
				retval = i;
			}
		}
		return retval;

	}

	@Override
	public Set<RdfTable> getTables(final RdfSchema schema) {
		final RdfCatalog catalog = schema.getCatalog();
		final Model model = schema.getResource().getModel();
		final RdfColumnDef.Builder colBuilder = new RdfColumnDef.Builder();
		colBuilder.setType(Types.VARCHAR)
		.setNullable(DatabaseMetaData.columnNoNulls).setReadOnly(true);
		// FIXME does this need a scale?
		idColumnDef = colBuilder.build(model);
		final HashSet<RdfTable> retval = new HashSet<RdfTable>();
		final List<QuerySolution> solns = catalog
				.executeQuery(SimpleNormalizingBuilder.TABLE_QUERY);
		for (final QuerySolution soln : solns) {
			buildTable(retval, catalog, schema, soln.getResource("tName"));
		}
		return retval;
	}

	protected RdfTable makeSubTable(final RdfCatalog catalog,
			final RdfSchema schema, final String tableQuerySegment,
			final String columnQuerySegment, final Resource tName,
			final Resource cName) {
		final Model model = catalog.getResource().getModel();

		final RdfTableDef.Builder tblDefBuilder = new RdfTableDef.Builder();

		tblDefBuilder.addColumnDef(idColumnDef);
		final RdfColumnDef.Builder builder = new RdfColumnDef.Builder();

		final int scale = calculateSize(catalog, tableQuerySegment,
				columnQuerySegment);
		builder.setType(Types.VARCHAR)
		.setNullable(DatabaseMetaData.columnNoNulls).setScale(scale)
		.setReadOnly(true);
		tblDefBuilder.addColumnDef(builder.build(model));

		// add the key segments
		RdfKeySegment.Builder keySegBuilder = new RdfKeySegment.Builder();
		keySegBuilder.setAscending(true);
		keySegBuilder.setIdx(0);

		final RdfKey.Builder keyBldr = new RdfKey.Builder();
		keyBldr.setUnique(true);
		keyBldr.addSegment(keySegBuilder.build(model));

		keySegBuilder = new RdfKeySegment.Builder();
		keySegBuilder.setAscending(true);
		keySegBuilder.setIdx(1);
		keyBldr.addSegment(keySegBuilder.build(model));

		tblDefBuilder.setPrimaryKey(keyBldr.build(model));

		// FIXME add foreign keys when avail

		final String tblName = String.format("%s%s", tName.getLocalName(),
				cName.getLocalName());

		final RdfTableDef tableDef = tblDefBuilder.build(model);
		final RdfTable.Builder tblBuilder = new RdfTable.Builder()
		.setTableDef(tableDef)
		.addQuerySegment(tableQuerySegment)
		.setName(tblName)
		.setSchema(schema)
		.setRemarks(
				"created by " + SimpleNormalizingBuilder.BUILDER_NAME);

		tblBuilder
		.setColumn(0, "id")
		.getColumn(0)
		.addQuerySegment(SimpleNormalizingBuilder.ID_COLUMN_SEGMENT)
		.setRemarks(
				"created by " + SimpleNormalizingBuilder.BUILDER_NAME);

		tblBuilder
		.setColumn(1, cName.getLocalName())
		.getColumn(1)
		.addQuerySegment(columnQuerySegment)
		.setRemarks(
				"created by " + SimpleNormalizingBuilder.BUILDER_NAME);

		return tblBuilder.build(model);
	}

	protected boolean multipleCardinality(final RdfCatalog catalog,
			final String tableQS, final String columnQS) {
		final String queryStr = String.format(
				"SELECT (count(*) as ?count) WHERE { %s %s } GROUP BY ?tbl",
				String.format(tableQS, "?tbl"),
				String.format(columnQS, "?tbl", "?col"));

		return WrappedIterator
				.create(catalog.executeQuery(queryStr).iterator())
				.filterKeep(new Filter<QuerySolution>() {

					@Override
					public boolean accept(final QuerySolution o) {
						return o.get("count").asLiteral().getInt() > 1;
					}
				}).hasNext();

	}
}


text:
package ti.modules.titanium.ui;

import org.appcelerator.kroll.annotations.Kroll;
import org.appcelerator.titanium.TiC;
import org.appcelerator.titanium.TiContext;
import org.appcelerator.titanium.proxy.TiViewProxy;
import org.appcelerator.titanium.view.TiUIView;

import ti.modules.titanium.ui.android.AndroidModule;
import ti.modules.titanium.ui.widget.TiUISwitch;
import android.app.Activity;

@Kroll.proxy(creatableInModule=UIModule.class,
propertyAccessors = {
	TiC.PROPERTY_VALUE,
	TiC.PROPERTY_STYLE,
	TiC.PROPERTY_TITLE,
	TiC.PROPERTY_TITLE_ON,
	TiC.PROPERTY_TITLE_OFF,
	TiC.PROPERTY_COLOR,
	TiC.PROPERTY_FONT,
	TiC.PROPERTY_TEXT_ALIGN,
	TiC.PROPERTY_VERTICAL_ALIGN
})
public class SwitchProxy extends TiViewProxy
{
	public SwitchProxy()
	{
		super();

		setProperty(TiC.PROPERTY_VALUE, false);
		setProperty(TiC.PROPERTY_STYLE, AndroidModule.SWITCH_STYLE_SWITCH);
	}

	public SwitchProxy(TiContext tiContext)
	{
		this();
	}

	@Override
	public TiUIView createView(Activity activity)
	{
		return new TiUISwitch(this);
	}

	@Override
	public String getApiName()
	{
		return "Ti.UI.Switch";
	}
}


text:
/** \file     TComPrediction.cpp
    \brief    prediction class
*/

#include <memory.h>
#include "TComPrediction.h"

//! \ingroup TLibCommon
//! \{

// ====================================================================================================================
// Constructor / destructor / initialize
// ====================================================================================================================

TComPrediction::TComPrediction()
: m_pLumaRecBuffer(0)
, m_iLumaRecStride(0)
{
  m_piYuvExt = NULL;
}

TComPrediction::~TComPrediction()
{

  delete[] m_piYuvExt;

  m_acYuvPred[0].destroy();
  m_acYuvPred[1].destroy();

  m_cYuvPredTemp.destroy();

  if( m_pLumaRecBuffer )
  {
    delete [] m_pLumaRecBuffer;
  }

  Int i, j;
  for (i = 0; i < 4; i++)
  {
    for (j = 0; j < 4; j++)
    {
      m_filteredBlock[i][j].destroy();
    }
    m_filteredBlockTmp[i].destroy();
  }
}

Void TComPrediction::initTempBuff()
{
  if( m_piYuvExt == NULL )
  {
    Int extWidth  = g_uiMaxCUWidth + 16;
    Int extHeight = g_uiMaxCUHeight + 1;
    Int i, j;
    for (i = 0; i < 4; i++)
    {
      m_filteredBlockTmp[i].create(extWidth, extHeight + 7);
      for (j = 0; j < 4; j++)
      {
        m_filteredBlock[i][j].create(extWidth, extHeight);
      }
    }
    m_iYuvExtHeight  = ((g_uiMaxCUHeight + 2) << 4);
    m_iYuvExtStride = ((g_uiMaxCUWidth  + 8) << 4);
    m_piYuvExt = new Int[ m_iYuvExtStride * m_iYuvExtHeight ];

    // new structure
    m_acYuvPred[0] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );
    m_acYuvPred[1] .create( g_uiMaxCUWidth, g_uiMaxCUHeight );

    m_cYuvPredTemp.create( g_uiMaxCUWidth, g_uiMaxCUHeight );
  }

  if (m_iLumaRecStride != (g_uiMaxCUWidth>>1) + 1)
  {
    m_iLumaRecStride =  (g_uiMaxCUWidth>>1) + 1;
    if (!m_pLumaRecBuffer)
    {
      m_pLumaRecBuffer = new Pel[ m_iLumaRecStride * m_iLumaRecStride ];
    }
  }
}

// ====================================================================================================================
// Public member functions
// ====================================================================================================================

// Function for calculating DC value of the reference samples used in Intra prediction
Pel TComPrediction::predIntraGetPredValDC( Int* pSrc, Int iSrcStride, UInt iWidth, UInt iHeight, Bool bAbove, Bool bLeft )
{
  Int iInd, iSum = 0;
  Pel pDcVal;

  if (bAbove)
  {
    for (iInd = 0;iInd < iWidth;iInd++)
    {
      iSum += pSrc[iInd-iSrcStride];
    }
  }
  if (bLeft)
  {
    for (iInd = 0;iInd < iHeight;iInd++)
    {
      iSum += pSrc[iInd*iSrcStride-1];
    }
  }

  if (bAbove && bLeft)
  {
    pDcVal = (iSum + iWidth) / (iWidth + iHeight);
  }
  else if (bAbove)
  {
    pDcVal = (iSum + iWidth/2) / iWidth;
  }
  else if (bLeft)
  {
    pDcVal = (iSum + iHeight/2) / iHeight;
  }
  else
  {
    pDcVal = pSrc[-1]; // Default DC value already calculated and placed in the prediction array if no neighbors are available
  }

  return pDcVal;
}

// Function for deriving the angular Intra predictions

/** Function for deriving the simplified angular intra predictions.
 * \param pSrc pointer to reconstructed sample array
 * \param srcStride the stride of the reconstructed sample array
 * \param rpDst reference to pointer for the prediction sample array
 * \param dstStride the stride of the prediction sample array
 * \param width the width of the block
 * \param height the height of the block
 * \param dirMode the intra prediction mode index
 * \param blkAboveAvailable boolean indication if the block above is available
 * \param blkLeftAvailable boolean indication if the block to the left is available
 *
 * This function derives the prediction samples for the angular mode based on the prediction direction indicated by
 * the prediction mode index. The prediction direction is given by the displacement of the bottom row of the block and
 * the reference row above the block in the case of vertical prediction or displacement of the rightmost column
 * of the block and reference column left from the block in the case of the horizontal prediction. The displacement
 * is signalled at 1/32 pixel accuracy. When projection of the predicted pixel falls inbetween reference samples,
 * the predicted value for the pixel is linearly interpolated from the reference samples. All reference samples are taken
 * from the extended main reference.
 */
Void TComPrediction::xPredIntraAng(Int bitDepth, Int* pSrc, Int srcStride, Pel*& rpDst, Int dstStride, UInt width, UInt height, UInt dirMode, Bool blkAboveAvailable, Bool blkLeftAvailable, Bool bFilter )
{
  Int k,l;
  Int blkSize        = width;
  Pel* pDst          = rpDst;

  // Map the mode index to main prediction direction and angle
  assert( dirMode > 0 ); //no planar
  Bool modeDC        = dirMode < 2;
  Bool modeHor       = !modeDC && (dirMode < 18);
  Bool modeVer       = !modeDC && !modeHor;
  Int intraPredAngle = modeVer ? (Int)dirMode - VER_IDX : modeHor ? -((Int)dirMode - HOR_IDX) : 0;
  Int absAng         = abs(intraPredAngle);
  Int signAng        = intraPredAngle < 0 ? -1 : 1;

  // Set bitshifts and scale the angle parameter to block size
  Int angTable[9]    = {0,    2,    5,   9,  13,  17,  21,  26,  32};
  Int invAngTable[9] = {0, 4096, 1638, 910, 630, 482, 390, 315, 256}; // (256 * 32) / Angle
  Int invAngle       = invAngTable[absAng];
  absAng             = angTable[absAng];
  intraPredAngle     = signAng * absAng;

  // Do the DC prediction
  if (modeDC)
  {
    Pel dcval = predIntraGetPredValDC(pSrc, srcStride, width, height, blkAboveAvailable, blkLeftAvailable);

    for (k=0;k<blkSize;k++)
    {
      for (l=0;l<blkSize;l++)
      {
        pDst[k*dstStride+l] = dcval;
      }
    }
  }

  // Do angular predictions
  else
  {
    Pel* refMain;
    Pel* refSide;
    Pel  refAbove[2*MAX_CU_SIZE+1];
    Pel  refLeft[2*MAX_CU_SIZE+1];

    // Initialise the Main and Left reference array.
    if (intraPredAngle < 0)
    {
      for (k=0;k<blkSize+1;k++)
      {
        refAbove[k+blkSize-1] = pSrc[k-srcStride-1];
      }
      for (k=0;k<blkSize+1;k++)
      {
        refLeft[k+blkSize-1] = pSrc[(k-1)*srcStride-1];
      }
      refMain = (modeVer ? refAbove : refLeft) + (blkSize-1);
      refSide = (modeVer ? refLeft : refAbove) + (blkSize-1);

      // Extend the Main reference to the left.
      Int invAngleSum    = 128;       // rounding for (shift by 8)
      for (k=-1; k>blkSize*intraPredAngle>>5; k--)
      {
        invAngleSum += invAngle;
        refMain[k] = refSide[invAngleSum>>8];
      }
    }
    else
    {
      for (k=0;k<2*blkSize+1;k++)
      {
        refAbove[k] = pSrc[k-srcStride-1];
      }
      for (k=0;k<2*blkSize+1;k++)
      {
        refLeft[k] = pSrc[(k-1)*srcStride-1];
      }
      refMain = modeVer ? refAbove : refLeft;
      refSide = modeVer ? refLeft  : refAbove;
    }

    if (intraPredAngle == 0)
    {
      for (k=0;k<blkSize;k++)
      {
        for (l=0;l<blkSize;l++)
        {
          pDst[k*dstStride+l] = refMain[l+1];
        }
      }

      if ( bFilter )
      {
        for (k=0;k<blkSize;k++)
        {
          pDst[k*dstStride] = Clip3(0, (1<<bitDepth)-1, pDst[k*dstStride] + (( refSide[k+1] - refSide[0] ) >> 1) );
        }
      }
    }
    else
    {
      Int deltaPos=0;
      Int deltaInt;
      Int deltaFract;
      Int refMainIndex;

      for (k=0;k<blkSize;k++)
      {
        deltaPos += intraPredAngle;
        deltaInt   = deltaPos >> 5;
        deltaFract = deltaPos & (32 - 1);

        if (deltaFract)
        {
          // Do linear filtering
          for (l=0;l<blkSize;l++)
          {
            refMainIndex        = l+deltaInt+1;
            pDst[k*dstStride+l] = (Pel) ( ((32-deltaFract)*refMain[refMainIndex]+deltaFract*refMain[refMainIndex+1]+16) >> 5 );
          }
        }
        else
        {
          // Just copy the integer samples
          for (l=0;l<blkSize;l++)
          {
            pDst[k*dstStride+l] = refMain[l+deltaInt+1];
          }
        }
      }
    }

    // Flip the block if this is the horizontal mode
    if (modeHor)
    {
      Pel  tmp;
      for (k=0;k<blkSize-1;k++)
      {
        for (l=k+1;l<blkSize;l++)
        {
          tmp                 = pDst[k*dstStride+l];
          pDst[k*dstStride+l] = pDst[l*dstStride+k];
          pDst[l*dstStride+k] = tmp;
        }
      }
    }
  }
}

Void TComPrediction::predIntraLumaAng(TComPattern* pcTComPattern, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft )
{
  Pel *pDst = piPred;
  Int *ptrSrc;

  assert( g_aucConvertToBit[ iWidth ] >= 0 ); //   4x  4
  assert( g_aucConvertToBit[ iWidth ] <= 5 ); // 128x128
  assert( iWidth == iHeight  );

  ptrSrc = pcTComPattern->getPredictorPtr( uiDirMode, g_aucConvertToBit[ iWidth ] + 2, m_piYuvExt );

  // get starting pixel in block
  Int sw = 2 * iWidth + 1;

  // Create the prediction
  if ( uiDirMode == PLANAR_IDX )
  {
    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
  }
  else
  {
    if ( (iWidth > 16) || (iHeight > 16) )
    {
      xPredIntraAng(g_bitDepthY, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, false );
    }
    else
    {
      xPredIntraAng(g_bitDepthY, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, true );

      if( (uiDirMode == DC_IDX ) && bAbove && bLeft )
      {
        xDCPredFiltering( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight);
      }
    }
  }
}

// Angular chroma
Void TComPrediction::predIntraChromaAng( Int* piSrc, UInt uiDirMode, Pel* piPred, UInt uiStride, Int iWidth, Int iHeight, Bool bAbove, Bool bLeft )
{
  Pel *pDst = piPred;
  Int *ptrSrc = piSrc;

  // get starting pixel in block
  Int sw = 2 * iWidth + 1;

  if ( uiDirMode == PLANAR_IDX )
  {
    xPredIntraPlanar( ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight );
  }
  else
  {
    // Create the prediction
    xPredIntraAng(g_bitDepthC, ptrSrc+sw+1, sw, pDst, uiStride, iWidth, iHeight, uiDirMode, bAbove, bLeft, false );
  }
}

/** Function for checking identical motion.
 * \param TComDataCU* pcCU
 * \param UInt PartAddr
 */
Bool TComPrediction::xCheckIdenticalMotion ( TComDataCU* pcCU, UInt PartAddr )
{
  if( pcCU->getSlice()->isInterB() && !pcCU->getSlice()->getPPS()->getWPBiPred() )
  {
    if( pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr) >= 0 && pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr) >= 0)
    {
      Int RefPOCL0 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_0, pcCU->getCUMvField(REF_PIC_LIST_0)->getRefIdx(PartAddr))->getPOC();
      Int RefPOCL1 = pcCU->getSlice()->getRefPic(REF_PIC_LIST_1, pcCU->getCUMvField(REF_PIC_LIST_1)->getRefIdx(PartAddr))->getPOC();
      if(RefPOCL0 == RefPOCL1 && pcCU->getCUMvField(REF_PIC_LIST_0)->getMv(PartAddr) == pcCU->getCUMvField(REF_PIC_LIST_1)->getMv(PartAddr))
      {
        return true;
      }
    }
  }
  return false;
}

Void TComPrediction::motionCompensation ( TComDataCU* pcCU, TComYuv* pcYuvPred, RefPicList eRefPicList, Int iPartIdx )
{
  Int         iWidth;
  Int         iHeight;
  UInt        uiPartAddr;

  if ( iPartIdx >= 0 )
  {
    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );
    if ( eRefPicList != REF_PIC_LIST_X )
    {
      if( pcCU->getSlice()->getPPS()->getUseWP())
      {
        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
      }
      else
      {
        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
      }
      if ( pcCU->getSlice()->getPPS()->getUseWP() )
      {
        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
      }
    }
    else
    {
      if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
      {
        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
      }
      else
      {
        xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
      }
    }
    return;
  }

  for ( iPartIdx = 0; iPartIdx < pcCU->getNumPartInter(); iPartIdx++ )
  {
    pcCU->getPartIndexAndSize( iPartIdx, uiPartAddr, iWidth, iHeight );

    if ( eRefPicList != REF_PIC_LIST_X )
    {
      if( pcCU->getSlice()->getPPS()->getUseWP())
      {
        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred, true );
      }
      else
      {
        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
      }
      if ( pcCU->getSlice()->getPPS()->getUseWP() )
      {
        xWeightedPredictionUni( pcCU, pcYuvPred, uiPartAddr, iWidth, iHeight, eRefPicList, pcYuvPred );
      }
    }
    else
    {
      if ( xCheckIdenticalMotion( pcCU, uiPartAddr ) )
      {
        xPredInterUni (pcCU, uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, pcYuvPred );
      }
      else
      {
        xPredInterBi  (pcCU, uiPartAddr, iWidth, iHeight, pcYuvPred );
      }
    }
  }
  return;
}

Void TComPrediction::xPredInterUni ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, RefPicList eRefPicList, TComYuv*& rpcYuvPred, Bool bi )
{
  Int         iRefIdx     = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );           assert (iRefIdx >= 0);
  TComMv      cMv         = pcCU->getCUMvField( eRefPicList )->getMv( uiPartAddr );
  pcCU->clipMv(cMv);
  xPredInterLumaBlk  ( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
  xPredInterChromaBlk( pcCU, pcCU->getSlice()->getRefPic( eRefPicList, iRefIdx )->getPicYuvRec(), uiPartAddr, &cMv, iWidth, iHeight, rpcYuvPred, bi );
}

Void TComPrediction::xPredInterBi ( TComDataCU* pcCU, UInt uiPartAddr, Int iWidth, Int iHeight, TComYuv*& rpcYuvPred )
{
  TComYuv* pcMbYuv;
  Int      iRefIdx[2] = {-1, -1};

  for ( Int iRefList = 0; iRefList < 2; iRefList++ )
  {
    RefPicList eRefPicList = (iRefList ? REF_PIC_LIST_1 : REF_PIC_LIST_0);
    iRefIdx[iRefList] = pcCU->getCUMvField( eRefPicList )->getRefIdx( uiPartAddr );

    if ( iRefIdx[iRefList] < 0 )
    {
      continue;
    }

    assert( iRefIdx[iRefList] < pcCU->getSlice()->getNumRefIdx(eRefPicList) );

    pcMbYuv = &m_acYuvPred[iRefList];
    if( pcCU->getCUMvField( REF_PIC_LIST_0 )->getRefIdx( uiPartAddr ) >= 0 && pcCU->getCUMvField( REF_PIC_LIST_1 )->getRefIdx( uiPartAddr ) >= 0 )
    {
      xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, true );
    }
    else
    {
      if ( ( pcCU->getSlice()->getPPS()->getUseWP()       && pcCU->getSlice()->getSliceType() == P_SLICE ) ||
           ( pcCU->getSlice()->getPPS()->getWPBiPred() && pcCU->getSlice()->getSliceType() == B_SLICE ) )
      {
        xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv, true );
      }
      else
      {
        xPredInterUni ( pcCU, uiPartAddr, iWidth, iHeight, eRefPicList, pcMbYuv );
      }
    }
  }

  if ( pcCU->getSlice()->getPPS()->getWPBiPred() && pcCU->getSlice()->getSliceType() == B_SLICE  )
  {
    xWeightedPredictionBi( pcCU, &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
  }
  else if ( pcCU->getSlice()->getPPS()->getUseWP() && pcCU->getSlice()->getSliceType() == P_SLICE )
  {
    xWeightedPredictionUni( pcCU, &m_acYuvPred[0], uiPartAddr, iWidth, iHeight, REF_PIC_LIST_0, rpcYuvPred );
  }
  else
  {
    xWeightedAverage( &m_acYuvPred[0], &m_acYuvPred[1], iRefIdx[0], iRefIdx[1], uiPartAddr, iWidth, iHeight, rpcYuvPred );
  }
}

/**
 * \brief Generate motion-compensated luma block
 *
 * \param cu       Pointer to current CU
 * \param refPic   Pointer to reference picture
 * \param partAddr Address of block within CU
 * \param mv       Motion vector
 * \param width    Width of block
 * \param height   Height of block
 * \param dstPic   Pointer to destination picture
 * \param bi       Flag indicating whether bipred is used
 */
Void TComPrediction::xPredInterLumaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi )
{
  Int refStride = refPic->getStride();
  Int refOffset = ( mv->getHor() >> 2 ) + ( mv->getVer() >> 2 ) * refStride;
  Pel *ref      = refPic->getLumaAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;

  Int dstStride = dstPic->getStride();
  Pel *dst      = dstPic->getLumaAddr( partAddr );

  Int xFrac = mv->getHor() & 0x3;
  Int yFrac = mv->getVer() & 0x3;

  if ( yFrac == 0 )
  {
    m_if.filterHorLuma( ref, refStride, dst, dstStride, width, height, xFrac,       !bi );
  }
  else if ( xFrac == 0 )
  {
    m_if.filterVerLuma( ref, refStride, dst, dstStride, width, height, yFrac, true, !bi );
  }
  else
  {
    Int tmpStride = m_filteredBlockTmp[0].getStride();
    Short *tmp    = m_filteredBlockTmp[0].getLumaAddr();

    Int filterSize = NTAPS_LUMA;
    Int halfFilterSize = ( filterSize >> 1 );

    m_if.filterHorLuma(ref - (halfFilterSize-1)*refStride, refStride, tmp, tmpStride, width, height+filterSize-1, xFrac, false     );
    m_if.filterVerLuma(tmp + (halfFilterSize-1)*tmpStride, tmpStride, dst, dstStride, width, height,              yFrac, false, !bi);
  }
}

/**
 * \brief Generate motion-compensated chroma block
 *
 * \param cu       Pointer to current CU
 * \param refPic   Pointer to reference picture
 * \param partAddr Address of block within CU
 * \param mv       Motion vector
 * \param width    Width of block
 * \param height   Height of block
 * \param dstPic   Pointer to destination picture
 * \param bi       Flag indicating whether bipred is used
 */
Void TComPrediction::xPredInterChromaBlk( TComDataCU *cu, TComPicYuv *refPic, UInt partAddr, TComMv *mv, Int width, Int height, TComYuv *&dstPic, Bool bi )
{
  Int     refStride  = refPic->getCStride();
  Int     dstStride  = dstPic->getCStride();

  Int     refOffset  = (mv->getHor() >> 3) + (mv->getVer() >> 3) * refStride;

  Pel*    refCb     = refPic->getCbAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;
  Pel*    refCr     = refPic->getCrAddr( cu->getAddr(), cu->getZorderIdxInCU() + partAddr ) + refOffset;

  Pel* dstCb = dstPic->getCbAddr( partAddr );
  Pel* dstCr = dstPic->getCrAddr( partAddr );

  Int     xFrac  = mv->getHor() & 0x7;
  Int     yFrac  = mv->getVer() & 0x7;
  UInt    cxWidth  = width  >> 1;
  UInt    cxHeight = height >> 1;

  Int     extStride = m_filteredBlockTmp[0].getStride();
  Short*  extY      = m_filteredBlockTmp[0].getLumaAddr();

  Int filterSize = NTAPS_CHROMA;

  Int halfFilterSize = (filterSize>>1);

  if ( yFrac == 0 )
  {
    m_if.filterHorChroma(refCb, refStride, dstCb,  dstStride, cxWidth, cxHeight, xFrac, !bi);
    m_if.filterHorChroma(refCr, refStride, dstCr,  dstStride, cxWidth, cxHeight, xFrac, !bi);
  }
  else if ( xFrac == 0 )
  {
    m_if.filterVerChroma(refCb, refStride, dstCb, dstStride, cxWidth, cxHeight, yFrac, true, !bi);
    m_if.filterVerChroma(refCr, refStride, dstCr, dstStride, cxWidth, cxHeight, yFrac, true, !bi);
  }
  else
  {
    m_if.filterHorChroma(refCb - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false);
    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCb, dstStride, cxWidth, cxHeight  , yFrac, false, !bi);

    m_if.filterHorChroma(refCr - (halfFilterSize-1)*refStride, refStride, extY,  extStride, cxWidth, cxHeight+filterSize-1, xFrac, false);
    m_if.filterVerChroma(extY  + (halfFilterSize-1)*extStride, extStride, dstCr, dstStride, cxWidth, cxHeight  , yFrac, false, !bi);
  }
}

Void TComPrediction::xWeightedAverage( TComYuv* pcYuvSrc0, TComYuv* pcYuvSrc1, Int iRefIdx0, Int iRefIdx1, UInt uiPartIdx, Int iWidth, Int iHeight, TComYuv*& rpcYuvDst )
{
  if( iRefIdx0 >= 0 && iRefIdx1 >= 0 )
  {
    rpcYuvDst->addAvg( pcYuvSrc0, pcYuvSrc1, uiPartIdx, iWidth, iHeight );
  }
  else if ( iRefIdx0 >= 0 && iRefIdx1 <  0 )
  {
    pcYuvSrc0->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
  }
  else if ( iRefIdx0 <  0 && iRefIdx1 >= 0 )
  {
    pcYuvSrc1->copyPartToPartYuv( rpcYuvDst, uiPartIdx, iWidth, iHeight );
  }
}

// AMVP
Void TComPrediction::getMvPredAMVP( TComDataCU* pcCU, UInt uiPartIdx, UInt uiPartAddr, RefPicList eRefPicList, TComMv& rcMvPred )
{
  AMVPInfo* pcAMVPInfo = pcCU->getCUMvField(eRefPicList)->getAMVPInfo();
  if( pcAMVPInfo->iN <= 1 )
  {
    rcMvPred = pcAMVPInfo->m_acMvCand[0];

    pcCU->setMVPIdxSubParts( 0, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
    pcCU->setMVPNumSubParts( pcAMVPInfo->iN, eRefPicList, uiPartAddr, uiPartIdx, pcCU->getDepth(uiPartAddr));
    return;
  }

  assert(pcCU->getMVPIdx(eRefPicList,uiPartAddr) >= 0);
  rcMvPred = pcAMVPInfo->m_acMvCand[pcCU->getMVPIdx(eRefPicList,uiPartAddr)];
  return;
}

/** Function for deriving planar intra prediction.
 * \param pSrc pointer to reconstructed sample array
 * \param srcStride the stride of the reconstructed sample array
 * \param rpDst reference to pointer for the prediction sample array
 * \param dstStride the stride of the prediction sample array
 * \param width the width of the block
 * \param height the height of the block
 *
 * This function derives the prediction samples for planar mode (intra coding).
 */
Void TComPrediction::xPredIntraPlanar( Int* pSrc, Int srcStride, Pel* rpDst, Int dstStride, UInt width, UInt height )
{
  assert(width == height);

  Int k, l, bottomLeft, topRight;
  Int horPred;
  Int leftColumn[MAX_CU_SIZE], topRow[MAX_CU_SIZE], bottomRow[MAX_CU_SIZE], rightColumn[MAX_CU_SIZE];
  UInt blkSize = width;
  UInt offset2D = width;
  UInt shift1D = g_aucConvertToBit[ width ] + 2;
  UInt shift2D = shift1D + 1;

  // Get left and above reference column and row
  for(k=0;k<blkSize+1;k++)
  {
    topRow[k] = pSrc[k-srcStride];
    leftColumn[k] = pSrc[k*srcStride-1];
  }

  // Prepare intermediate variables used in interpolation
  bottomLeft = leftColumn[blkSize];
  topRight   = topRow[blkSize];
  for (k=0;k<blkSize;k++)
  {
    bottomRow[k]   = bottomLeft - topRow[k];
    rightColumn[k] = topRight   - leftColumn[k];
    topRow[k]      <<= shift1D;
    leftColumn[k]  <<= shift1D;
  }

  // Generate prediction signal
  for (k=0;k<blkSize;k++)
  {
    horPred = leftColumn[k] + offset2D;
    for (l=0;l<blkSize;l++)
    {
      horPred += rightColumn[k];
      topRow[l] += bottomRow[l];
      rpDst[k*dstStride+l] = ( (horPred + topRow[l]) >> shift2D );
    }
  }
}

/** Function for filtering intra DC predictor.
 * \param pSrc pointer to reconstructed sample array
 * \param iSrcStride the stride of the reconstructed sample array
 * \param rpDst reference to pointer for the prediction sample array
 * \param iDstStride the stride of the prediction sample array
 * \param iWidth the width of the block
 * \param iHeight the height of the block
 *
 * This function performs filtering left and top edges of the prediction samples for DC mode (intra coding).
 */
Void TComPrediction::xDCPredFiltering( Int* pSrc, Int iSrcStride, Pel*& rpDst, Int iDstStride, Int iWidth, Int iHeight )
{
  Pel* pDst = rpDst;
  Int x, y, iDstStride2, iSrcStride2;

  // boundary pixels processing
  pDst[0] = (Pel)((pSrc[-iSrcStride] + pSrc[-1] + 2 * pDst[0] + 2) >> 2);

  for ( x = 1; x < iWidth; x++ )
  {
    pDst[x] = (Pel)((pSrc[x - iSrcStride] +  3 * pDst[x] + 2) >> 2);
  }

  for ( y = 1, iDstStride2 = iDstStride, iSrcStride2 = iSrcStride-1; y < iHeight; y++, iDstStride2+=iDstStride, iSrcStride2+=iSrcStride )
  {
    pDst[iDstStride2] = (Pel)((pSrc[iSrcStride2] + 3 * pDst[iDstStride2] + 2) >> 2);
  }

  return;
}
//! \}


text:
SPARKX=/nx/software/spark
ARTIFACTS=$PWD/out/artifacts

CLS=$1
shift

# $SPARKX/bin/spark-submit --conf spark.sql.codegen=true --jars $ARTIFACTS/squark_jar/squark.jar --class com.vitessedata.examples.quark.$CLS $ARTIFACTS/examples_jar/examples.jar $1 sql "$2"
$SPARKX/bin/spark-submit --master local[2] --conf spark.sql.shuffle.partitions=16 --conf spark.executor.memory=2g --jars $ARTIFACTS/squark_jar/squark.jar --class com.vitessedata.examples.quark.$CLS $ARTIFACTS/examples_jar/examples.jar $1 sql "$2"


text:
Ribbit is a library providing scoring advice about consumers based on their income, zipcode, and age. This is an API Integration exercise for LeapFrog Online.

### Guide to Install Gem
+ Clone this repository
+ In termial navigate to the imported repo
+ Using the gemspec build the ribbit gem - type:
```
    gem build ribbit.gemspec
```
+ Upon success you may install the gem - type:
```
    gem install ./ribbit-0.0.0.gem
```
+ Included in this library are testing suites for the ribbit library as well as a demo program implementation. To run specs for both navigate to the spec file of your choosing and - type:
```
    rspec INSERT FILENAME HERE
```

*Note: This library includes a fictional HTTP destination - for implementing in actual development scenarios you must change the destination source in the ribbit.rb file*

### Other Gems Required for Functionality
Before installing ensure you have the following gems installed locally. See Ruby-Toolbox.com for more instructions.
 + WebMock ('webmock/rspec')
 + Net/Http ('net/http')
 + Json ('json')

### Guide to use Demo Program

Also included in this repository is a program to calculate and view  consumer ratings easily with the Ribbit gem.

*Note: income, zipcode, and age values must be present, fixnums, in hash format to be valid.*

```ruby
require 'ribbit'
rating_data = ConsumerRating.new( income:  50000,
                                  zipcode: 60201,
                                  age:     35 )

rating_data.ranking #=> 'C'
rating_data.propensity #=> 2.26532
rating_data.display # will display the following in stdout: "Ranking: C, Propensity: 2.26532"
```


text:
using Microsoft.Extensions.Localization;

namespace System.ComponentModel.DataAnnotations
{
	[AttributeUsage(AttributeTargets.Property)]
	public sealed class RequiredValueAttribute : ValidationAttribute
	{
		private object valueToCompare;

		public RequiredValueAttribute(object valueToCompare)
			: this(valueToCompare, "The value for field {0} does not match required one.")
		{
		}

		public RequiredValueAttribute(object valueToCompare, Func<string> errorMessageAccessor)
			: base(errorMessageAccessor)
		{
			this.valueToCompare = valueToCompare;
		}

		public RequiredValueAttribute(object valueToCompare, string errorMessage)
			: base(errorMessage)
		{
			this.valueToCompare = valueToCompare;
		}

		public override bool IsValid(object value)
			=> valueToCompare?.Equals(value) ?? false;

		public void TranslatErrorMessage(IStringLocalizer translator)
			=> this.ErrorMessage = translator.GetString(this.ErrorMessageString);
	}
}


text:
<?php
App::uses('AppController', 'Controller');

class BlockAppController extends AppController
{
  public $uses = array('Block');
  public $components = array('Api');

  public function beforeFilter()
  {
    parent::beforeFilter();
  }

}


text:
- docker 1.8.x
- docker-compose

### Container Descriptions:
This application makes use of docker containerization. This is accomplished across 4 containers.

Their descriptions are outlined as follows:

1. *mediadrop-uwsgi* - Based in debian:jessie. On first start it checks if mediadrop has been and installed. If not, it will:
    * Clone the mediadrop repo from github this build was based on
    * Activates python virtual enviroment
    * Installs mediadrop from source
    * Adds customizations fto the deployment.ini
    * Configures UWSGI service in socket mode
    * Checks if database is not populated and runs the database scripts and optional databse search tables to the connected mediadtop-mariadb container

*Note: See [start.sh] (https://github.com/nmarus/docker-mediadrop/blob/master/uwsgi/start.sh)*

2. *mediadrop-nginx* - Based on official docker nginx image with customized.
nginx configuration, and self signed certs.

*Note: By default, the nginx.conf runs non SSL to get around the Adobe Flash player requirements that do not work with self signed certificates for file upload in regard the ["File I/O Error #2038."] (http://stackoverflow.com/questions/1789863/swfupload-on-https-not-working) To enable SSL, and continue to have file uploads work, you must use a trusted CA signed certificate. (This seems to only affect MAC versions of the flashplayer) See SSL section below under Advanced Configuration.)*

3. *mediadrop-mariadb* - Based on official docker mariadb image. Uses environment variables defined in the docker-compose.yml to setup the mediadrop database.

### Quick Start:

1. Clone this repository

        $ git clone https://github.com/nmarus/docker-mediadrop.git

2. Modify docker-compose.yml - Edit environment variables to include specifics for
deployment. It will however, work as-is.

3. Build the images - This script creates the docker images on the connected docker server.

        $ ./build.sh all

4. Run mediadrop - This starts all the images and create appropriate links between each container.

        $ docker-compose up -d

5. Wait approximately 5-10 minutes for the initial build before attempting to access the web interface.

### Advanced:

#### Enable SSL:

1. Modify the nginx/nginx.conf file
    - Remove the commented sections while also commenting out or removing the "listen 80" line in the main server section
    - Replace "<fqdn>" with the CNAME used to generate your CA signed certificates (i.e. video.example.com)

2. Upload your certificate and public key to the nginx folder replacing the self signed key found there. Make sure you use the same file names and have concatenated the intermediary certificates if required by your CA.

3. If you have already tested this with out SSL enabled, make sure you the mediadrop-nginx container from previous build.

        $ docker-compose stop
        $ docker-compose rm mediadrop-nginx

4. Rebuild the nginx image

        $ ./build.sh nginx

5. Restart mediadrop

        $ docker-compose up -d

#### Enable Volume Mapping

These steps will ensure that you have the non persistent files stored to your docker host. These changes are made from the docker-compose.yml file.

1. Enable the persistent data volumes for "mediadrop-uwsgi":

        volumes:
            - /local/path/for/wsgi:/wsgi
            - /local/path/for/mediadrop:/mediadrop
            - /local/path/for/venv:/venv

2. Enable the persistent data volume for "mediadrop-mariadb":

        volumes:
            - /local/path/for/mysql:/var/lib/mysql

#### Enable the Mediadrop Official Repository
The installer script downloads a snapshot of the mediadrop repositry as it was on October 17th, 2015. If you wish to download the latest updates, do the following.

###### Note 1: Depending on how much has changed in the repository, these scripts may not work.

###### Note 2: If you have not enabled the storing of non persistent data outside of docker, your current setup will be reset to default.

1. Add an environment variable to the mediadrop-uwsgi section of the docker-compose.yml file.

        environment:
            - USE_OFFICIAL_GIT=true

2. Remove containers and redeploy images with new docker-compose.yml file.

        $ docker-compose stop
        $ docker-compose rm -f
        $ docker-compose up -d


text:
'use strict';

angular.module('myApp.viewHomepage', ['ngRoute', 'ui.bootstrap'])

.config(['$routeProvider', function($routeProvider) {
  $routeProvider.when('/viewHomepage', {
    templateUrl: 'viewHomepage/viewHomepage.html',
    controller: 'ViewHomepageCtrl'
  });
}])

.controller('ViewHomepageCtrl', [function() {

}]);

/*
.controller('ViewHomepageCtrl', function ($scope, $modal, $filter, Data) {
    $scope.product = {};
    Data.get('products').then(function(data){
        $scope.products = data.data;
    });
    $scope.changeProductStatus = function(product){
        product.status = (product.status=="Active" ? "Inactive" : "Active");
        Data.put("products/"+product.id,{status:product.status});
    };
    $scope.deleteProduct = function(product){
        if(confirm("Are you sure to remove the product")){
            Data.delete("products/"+product.id).then(function(result){
                $scope.products = _.without($scope.products, _.findWhere($scope.products, {id:product.id}));
            });
        }
    };
    $scope.open = function (p,size) {
        var modalInstance = $modal.open({
          templateUrl: 'partials/productEdit.html',
          controller: 'productEditCtrl',
          size: size,
          resolve: {
            item: function () {
              return p;
            }
          }
        });
        modalInstance.result.then(function(selectedObject) {
            if(selectedObject.save == "insert"){
                $scope.products.push(selectedObject);
                $scope.products = $filter('orderBy')($scope.products, 'id', 'reverse');
            }else if(selectedObject.save == "update"){
                p.description = selectedObject.description;
                p.price = selectedObject.price;
                p.stock = selectedObject.stock;
                p.packing = selectedObject.packing;
            }
        });
    };

 $scope.columns = [
                    {text:"ID",predicate:"id",sortable:true,dataType:"number"},
                    {text:"Name",predicate:"name",sortable:true},
                    {text:"Price",predicate:"price",sortable:true},
                    {text:"Stock",predicate:"stock",sortable:true},
                    {text:"Packing",predicate:"packing",reverse:true,sortable:true,dataType:"number"},
                    {text:"Description",predicate:"description",sortable:true},
                    {text:"Status",predicate:"status",sortable:true},
                    {text:"Action",predicate:"",sortable:false}
                ];

})

.controller('productEditCtrl', function ($scope, $modalInstance, item, Data) {

  $scope.product = angular.copy(item);

        $scope.cancel = function () {
            $modalInstance.dismiss('Close');
        };
        $scope.title = (item.id > 0) ? 'Edit Product' : 'Add Product';
        $scope.buttonText = (item.id > 0) ? 'Update Product' : 'Add New Product';

        var original = item;
        $scope.isClean = function() {
            return angular.equals(original, $scope.product);
        }
        $scope.saveProduct = function (product) {
            product.uid = $scope.uid;
            if(product.id > 0){
                Data.put('products/'+product.id, product).then(function (result) {
                    if(result.status != 'error'){
                        var x = angular.copy(product);
                        x.save = 'update';
                        $modalInstance.close(x);
                    }else{
                        console.log(result);
                    }
                });
            }else{
                product.status = 'Active';
                Data.post('products', product).then(function (result) {
                    if(result.status != 'error'){
                        var x = angular.copy(product);
                        x.save = 'insert';
                        x.id = result.data;
                        $modalInstance.close(x);
                    }else{
                        console.log(result);
                    }
                });
            }
        };
})

.factory("Data", ['$http', '$location',
    function ($http, $q, $location) {

        var serviceBase = 'api/v1/';

        var obj = {};

        obj.get = function (q) {
            return $http.get(serviceBase + q).then(function (results) {
                return results.data;
            });
        };
        obj.post = function (q, object) {
            return $http.post(serviceBase + q, object).then(function (results) {
                return results.data;
            });
        };
        obj.put = function (q, object) {
            return $http.put(serviceBase + q, object).then(function (results) {
                return results.data;
            });
        };
        obj.delete = function (q) {
            return $http.delete(serviceBase + q).then(function (results) {
                return results.data;
            });
        };
        return obj;
}]);
*/


text:
define(['app/mwtnSpectrum/mwtnSpectrum.module'],function(mwtnSpectrumApp) {

  mwtnSpectrumApp.register.factory('$mwtnSpectrum', function($http, ENV) {
    var service = {
      base: ENV.getBaseURL("MD_SAL") + "/restconf/"
    };

    /*
     * You can define all of your REST API interactions here.
     */

    return service;
  });

});


text:
var APIOptions, Hash, ReturnValue, Singleton, config_path, fs, path, _,
  __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; },
  __hasProp = {}.hasOwnProperty;

_ = require('lodash')._;

Hash = require('strictly-hash');

fs = require('fs');

path = require('path');

Singleton = require('../base_class/Singleton');

config_path = "" + (process.cwd()) + path.sep + "server" + path.sep + "api-hero.json";

APIOptions = (function(_super) {
  __extends(APIOptions, _super);

  function APIOptions() {
    var o, params;
    params = fs.existsSync(config_path) ? require(config_path) : {};
    APIOptions.__super__.constructor.call(this, o = _.extend({
      api_basepath: '/api',
      api_version: '',
      api_path: '',
      api_namespace: '',
      schema_path: "" + (process.cwd()) + path.sep + "schemas",
      schema_api_require_path: "" + (process.cwd()) + path.sep + ".api-hero",
      data_path: "" + (process.cwd()) + path.sep + ".api-hero",
      trees_path: "" + (process.cwd()) + path.sep + ".api-hero" + path.sep + "trees",
      destructive: false,
      wrap_schema_exports: true,
      debug: process.NODE_ENV === void 0 || process.NODE_ENV === 'development',
      default_datasource: 'mongo',
      server_dir: './server'
    }, params), _.keys(o));
    this.set('api_path', (this.get('api_basepath')) + "/" + (this.get('api_version')) + "/");
  }

  return APIOptions;

})(Hash);

ReturnValue = (function(_super) {
  __extends(ReturnValue, _super);

  function ReturnValue() {
    this.__opts = new APIOptions;
  }

  ReturnValue.prototype.getOpts = function() {
    return this.__opts;
  };

  return ReturnValue;

})(Singleton);

module.exports = ReturnValue.getInstance().getOpts();


text:
#ifndef BABYLON_MATERIALS_NODE_NODE_MATERIAL_BUILD_STATE_H
#define BABYLON_MATERIALS_NODE_NODE_MATERIAL_BUILD_STATE_H

#include <memory>
#include <string>
#include <unordered_map>
#include <vector>

#include <babylon/babylon_api.h>
#include <babylon/babylon_common.h>
#include <babylon/babylon_fwd.h>
#include <babylon/materials/node/enums/node_material_block_connection_point_types.h>
#include <babylon/materials/node/enums/node_material_block_targets.h>

namespace BABYLON {

class NodeMaterialBuildState;
struct NodeMaterialBuildStateSharedData;
struct ReplaceStrings;
FWD_CLASS_SPTR(NodeMaterialBuildState)
FWD_STRUCT_SPTR(NodeMaterialBuildStateSharedData)

struct BABYLON_SHARED_EXPORT StringsReplacement {
  std::string search  = "";
  std::string replace = "";
}; // end of struct StringsReplacement

struct BABYLON_SHARED_EXPORT EmitCodeFromIncludeOptions {
  std::vector<StringsReplacement> replaceStrings = {};
  std::string repeatKey                          = "";
}; // end of struct _emitCodeFromIncludeOptions

struct BABYLON_SHARED_EXPORT EmitFunctionFromIncludeOptions {
  std::string repeatKey                          = "";
  std::optional<bool> removeAttributes           = std::nullopt;
  std::optional<bool> removeUniforms             = std::nullopt;
  std::optional<bool> removeVaryings             = std::nullopt;
  std::optional<bool> removeIfDef                = std::nullopt;
  std::vector<StringsReplacement> replaceStrings = {};
}; // end of struct EmitFunctionFromIncludeOptions

/**
 * @brief Class used to store node based material build state.
 */
class BABYLON_SHARED_EXPORT NodeMaterialBuildState {

public:
  NodeMaterialBuildState();
  ~NodeMaterialBuildState() = default;

  /**
   * @brief Hidden
   */
  std::string _repeatableContentAnchor();

  /**
   * @brief Finalize the compilation strings.
   * @param state defines the current compilation state
   */
  void finalize(const NodeMaterialBuildState& state);

  /**
   * @brief Hidden
   */
  std::string _getFreeVariableName(std::string prefix);

  /**
   * @brief Hidden
   */
  std::string _getFreeDefineName(const std::string& prefix);

  /**
   * @brief Hidden
   */
  void _excludeVariableName(const std::string& name);

  /**
   * @brief Hidden
   */
  void _emit2DSampler(const std::string& name);

  /**
   * @brief Hidden
   */
  std::string _getGLType(NodeMaterialBlockConnectionPointTypes type) const;

  /**
   * @brief Hidden
   */
  void _emitExtension(const std::string& name, std::string extension,
                      const std::string& define = "");

  /**
   * @brief Hidden
   */
  void _emitFunction(const std::string& name, std::string code, const std::string& comments);

  /**
   * @brief Hidden
   */
  std::string _emitCodeFromInclude(const std::string& includeName, const std::string& comments,
                                   const std::optional<EmitCodeFromIncludeOptions>& options
                                   = std::nullopt);

  /**
   * @brief Hidden
   */
  void _emitFunctionFromInclude(const std::string& includeName, const std::string& comments,
                                const std::optional<EmitFunctionFromIncludeOptions>& options
                                = std::nullopt,
                                const std::string& storeKey = "");

  /**
   * @brief Hidden
   */
  bool _registerTempVariable(const std::string& name);

  /**
   * @brief Hidden
   */
  bool _emitVaryingFromString(const std::string& name, const std::string& type,
                              const std::string& define = "", bool notDefine = false);

  /**
   * @brief Hidden
   */
  void _emitUniformFromString(const std::string& name, const std::string& type,
                              const std::string& define = "", bool notDefine = false);

  /**
   * @brief Hidden
   */
  std::string _emitFloat(float value);

protected:
  /**
   * @brief Hidden
   */
  std::string get__repeatableContentAnchor();

public:
  /**
   * Gets or sets a boolean indicating if the current state can emit uniform buffers
   */
  bool supportUniformBuffers;
  /**
   * Gets the list of emitted attributes
   */
  std::vector<std::string> attributes;
  /**
   * Gets the list of emitted uniforms
   */
  std::vector<std::string> uniforms;
  /**
   * Gets the list of emitted constants
   */
  std::vector<std::string> constants;
  /**
   * Gets the list of emitted samplers
   */
  std::vector<std::string> samplers;
  /**
   * Gets the list of emitted functions
   */
  std::unordered_map<std::string, std::string> functions;
  /**
   * Gets the list of emitted extensions
   */
  std::unordered_map<std::string, std::string> extensions;

  /**
   * Gets the target of the compilation state
   */
  NodeMaterialBlockTargets target;
  /**
   * Gets the list of emitted counters
   */
  std::unordered_map<std::string, unsigned int> counters;

  /**
   * Shared data between multiple NodeMaterialBuildState instances
   */
  NodeMaterialBuildStateSharedDataPtr sharedData;

  /** @hidden */
  NodeMaterialBuildStatePtr _vertexState;

  /** @hidden */
  std::string _attributeDeclaration;
  /** @hidden */
  std::string _uniformDeclaration;
  /** @hidden */
  std::string _constantDeclaration;
  /** @hidden */
  std::string _samplerDeclaration;
  /** @hidden */
  std::string _varyingTransfer;
  /** @hidden */
  std::string _injectAtEnd;

  /** @hidden */
  std::string _builtCompilationString;

  /**
   * Gets the emitted compilation strings
   */
  std::string compilationString;

private:
  size_t _repeatableContentAnchorIndex;

}; // end of enum class NodeMaterialBuildState

} // end of namespace BABYLON

#endif // end of BABYLON_MATERIALS_NODE_NODE_MATERIAL_BUILD_STATE_H


text:
set -e
set -x

## Upgrade all packages.
apt-get update -y


text:
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Reflection;
using System.Security.Cryptography;
using System.Text;
using System.Web;
using Beyova;
using Beyova.ProgrammingIntelligence;

namespace Beyova
{
    /// <summary>
    /// Class EnvironmentCore.
    /// </summary>
    public static class EnvironmentCore
    {
        /// <summary>
        /// The application base directory
        /// </summary>
        public static readonly string ApplicationBaseDirectory;

        /// <summary>
        /// The log directory
        /// </summary>
        public static readonly string LogDirectory;

        /// <summary>
        /// The application identifier
        /// </summary>
        public static readonly int ApplicationId;

        /// <summary>
        /// The server name
        /// </summary>
        public static readonly string ServerName;

        /// <summary>
        /// The local machine host name
        /// </summary>
        public static readonly string LocalMachineHostName = string.Empty;

        /// <summary>
        /// The local machine ip address
        /// </summary>
        public static readonly string LocalMachineIpAddress = string.Empty;

        /// <summary>
        /// Gets the name of the product.
        /// </summary>
        /// <value>The name of the product.</value>
        public static string ProductName { get; private set; }

        /// <summary>
        /// The descending assembly dependency chain. Descending here means order by referenced amount.
        /// So result would be like: web -> core -> contract - > common -> json.net, etc.
        /// </summary>
        internal static List<Assembly> DescendingAssemblyDependencyChain;

        /// <summary>
        /// The ascending assembly dependency chain
        /// </summary>
        internal static List<Assembly> AscendingAssemblyDependencyChain;

        /// <summary>
        /// Gets the entry assembly.
        /// </summary>
        /// <value>
        /// The entry assembly.
        /// </value>
        public static Assembly EntryAssembly { get { return DescendingAssemblyDependencyChain.FirstOrDefault(); } }

        /// <summary>
        /// Initializes static members of the <see cref="EnvironmentCore"/> class.
        /// </summary>
        static EnvironmentCore()
        {
            ApplicationBaseDirectory = !string.IsNullOrWhiteSpace(HttpRuntime.AppDomainAppVirtualPath)
                ? Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "bin")
                : AppDomain.CurrentDomain.BaseDirectory;

            LogDirectory = Path.Combine(ApplicationBaseDirectory, "logs");
            ApplicationId = System.AppDomain.CurrentDomain.Id;

            DescendingAssemblyDependencyChain = ReflectionExtension.GetAppDomainAssemblies().GetAssemblyDependencyChain(true);
            AscendingAssemblyDependencyChain = new List<Assembly>(DescendingAssemblyDependencyChain);
            DescendingAssemblyDependencyChain.Reverse();

            try
            {
                ServerName = Environment.MachineName;
            }
            catch { ServerName = string.Empty; }

            try
            {
                LocalMachineHostName = Dns.GetHostName();

                var host = Dns.GetHostEntry(LocalMachineHostName);
                foreach (var ip in host.AddressList)
                {
                    if (ip.AddressFamily == AddressFamily.InterNetwork)
                    {
                        LocalMachineIpAddress = ip.ToString();
                        break;
                    }
                }
            }
            catch { }

            try
            {
                if (AppDomain.CurrentDomain != null)
                {
                    ProductName = AppDomain.CurrentDomain.FriendlyName;
                }

                if (string.IsNullOrWhiteSpace(ProductName) || ProductName.IndexOfAny(new char[] { '/', '\\', ':', '*' }) > -1)
                {
                    ProductName = Assembly.GetEntryAssembly()?.FullName;
                }

                if (string.IsNullOrWhiteSpace(ProductName))
                {
                    ProductName = FindProductName();
                }
            }
            catch { ProductName = string.Empty; }
        }

        /// <summary>
        /// Gets the total memory. Unit: bytes
        /// </summary>
        /// <value>The total memory.</value>
        public static long TotalMemory
        {
            get
            {
                return GC.GetTotalMemory(false);
            }
        }

        /// <summary>
        /// Finds the name of the product.
        /// </summary>
        /// <returns>System.String.</returns>
        private static string FindProductName()
        {
            try
            {
                string result = null;
                foreach (var one in DescendingAssemblyDependencyChain)
                {
                    var component = one.GetCustomAttribute<BeyovaComponentAttribute>();
                    if (component != null && !string.IsNullOrWhiteSpace(component.Id))
                    {
                        result = component.Id;
                        break;
                    }
                }

                if (string.IsNullOrWhiteSpace(result))
                {
                    result = DescendingAssemblyDependencyChain.FirstOrDefault()?.GetName()?.Name;
                }

                return result;
            }
            catch (Exception ex)
            {
                throw ex.Handle();
            }
        }

        /// <summary>
        /// Gets the directory.
        /// </summary>
        /// <param name="directory">The directory.</param>
        /// <param name="defaultSubDirectoryName">Default name of the sub directory.</param>
        /// <returns>System.IO.DirectoryInfo.</returns>
        internal static DirectoryInfo GetDirectory(string directory, string defaultSubDirectoryName = null)
        {
            string directoryPath;
            if (string.IsNullOrWhiteSpace(directory))
            {
                directoryPath = string.IsNullOrWhiteSpace(defaultSubDirectoryName) ? EnvironmentCore.ApplicationBaseDirectory : Path.Combine(EnvironmentCore.ApplicationBaseDirectory, defaultSubDirectoryName);
            }
            else if (directory.Contains(':') || directory.StartsWith("\\\\"))
            {
                directoryPath = directory;
            }
            else
            {
                directoryPath = directory.TrimStart('/', '~', '.').TrimEnd('/', '\\').Replace('/', '\\');
                directoryPath = string.IsNullOrWhiteSpace(directoryPath) ? EnvironmentCore.ApplicationBaseDirectory : Path.Combine(EnvironmentCore.ApplicationBaseDirectory, directoryPath);
            }

            return new DirectoryInfo(directoryPath);
        }

        /// <summary>
        /// Gets the assembly hash.
        /// </summary>
        /// <returns>System.String.</returns>
        internal static string GetAssemblyHash()
        {
            try
            {
                StringBuilder builder = new StringBuilder(DescendingAssemblyDependencyChain.Count * 16);
                MD5CryptoServiceProvider md5Provider = new MD5CryptoServiceProvider();

                foreach (var one in DescendingAssemblyDependencyChain)
                {
                    builder.Append(md5Provider.ComputeHash(File.ReadAllBytes(one.Location)).EncodeBase64());
                }

                return md5Provider.ComputeHash(Encoding.UTF8.GetBytes(builder.ToString())).EncodeBase64();
            }
            catch
            {
                return string.Empty;
            }
        }
    }
}