text:
const shell = require('shelljs');

const _run = (command) => {
	command += ' --json';
	const exec = shell.exec(command, { silent: true });
	let stdout;

	try {
		stdout = JSON.parse(exec.stdout);
	}catch(e) {
		throw new Error('Error parsing stdout', { cause: e });
	}

	if (stdout.status == 1){
		const error = new Error(`Command responded with error: ${command}`);
		throw Object.assign(error , { stdout });
	}

	if (exec.code === 1){
		const error = new Error(`Process error while running: ${command}`);
		throw Object.assign(error , { stderr: exec.stderr, code: exec.code });
	}

	return stdout.result;
}

const _sourceConvert = async (rootdir, outputdir) => {
	return _run(`sfdx force:source:convert --rootdir "${rootdir}" --outputdir "${outputdir}"`);
}

const _mdapiDeploy = async (targetusername, deploydir) => {
	return _run(`sfdx force:mdapi:deploy --deploydir "${deploydir}" --targetusername "${targetusername}" -w -1 --verbose`);
}

const run = async(command, options) => {
	if (command === 'source:convert') {
		return _sourceConvert(options.rootdir, options.outputdir);
	} else if (command === 'mdapi:deploy'){
		return _mdapiDeploy(options.targetusername, options.deploydir);
	}
}

module.exports = {
	run
}


text:
#ifndef __itkSquaredEdgeLengthDecimationQuadEdgeMeshFilter_h
#define __itkSquaredEdgeLengthDecimationQuadEdgeMeshFilter_h

#include "itkEdgeDecimationQuadEdgeMeshFilter.h"

namespace itk
{
/**
 * \class SquaredEdgeLengthDecimationQuadEdgeMeshFilter
 * \brief
 * \ingroup ITK-QuadEdgeMeshFiltering
 */
template< class TInput, class TOutput, class TCriterion >
class ITK_EXPORT SquaredEdgeLengthDecimationQuadEdgeMeshFilter:
  public EdgeDecimationQuadEdgeMeshFilter< TInput, TOutput, TCriterion >
{
public:
  typedef SquaredEdgeLengthDecimationQuadEdgeMeshFilter Self;
  typedef SmartPointer< Self >                          Pointer;
  typedef SmartPointer< const Self >                    ConstPointer;
  typedef EdgeDecimationQuadEdgeMeshFilter<
    TInput, TOutput, TCriterion >                       Superclass;

  /** Run-time type information (and related methods).   */
  itkTypeMacro(SquaredEdgeLengthDecimationQuadEdgeMeshFilter, EdgeDecimationQuadEdgeMeshFilter);

  /** New macro for creation of through a Smart Pointer   */
  itkNewMacro(Self);

  typedef TInput                          InputMeshType;
  typedef typename InputMeshType::Pointer InputMeshPointer;

  typedef TOutput                                         OutputMeshType;
  typedef typename OutputMeshType::Pointer                OutputMeshPointer;
  typedef typename OutputMeshType::PointIdentifier        OutputPointIdentifier;
  typedef typename OutputMeshType::PointType              OutputPointType;
  typedef typename OutputMeshType::QEType                 OutputQEType;
  typedef typename OutputMeshType::EdgeCellType           OutputEdgeCellType;
  typedef typename OutputMeshType::CellsContainerIterator OutputCellsContainerIterator;

  typedef TCriterion                          CriterionType;
  typedef typename CriterionType::MeasureType MeasureType;

  typedef typename Superclass::PriorityType          PriorityType;
  typedef typename Superclass::PriorityQueueItemType PriorityQueueItemType;
  typedef typename Superclass::PriorityQueueType     PriorityQueueType;
  typedef typename Superclass::PriorityQueuePointer  PriorityQueuePointer;

  typedef typename Superclass::QueueMapType     QueueMapType;
  typedef typename Superclass::QueueMapIterator QueueMapIterator;

  typedef typename Superclass::OperatorType    OperatorType;
  typedef typename Superclass::OperatorPointer OperatorPointer;
protected:

  SquaredEdgeLengthDecimationQuadEdgeMeshFilter();
  virtual ~SquaredEdgeLengthDecimationQuadEdgeMeshFilter();

  /**
   * \brief Compute the measure value for iEdge
   * \param[in] iEdge
   * \return measure value, here the squared edge length
   */
  inline MeasureType MeasureEdge(OutputQEType *iEdge)
  {
    OutputMeshPointer output = this->GetOutput();

    OutputPointIdentifier id_org = iEdge->GetOrigin();
    OutputPointIdentifier id_dest = iEdge->GetDestination();

    OutputPointType org = output->GetPoint(id_org);
    OutputPointType dest = output->GetPoint(id_dest);

    return static_cast< MeasureType >( org.SquaredEuclideanDistanceTo(dest) );
  }

  /**
   * \param[in] iEdge
   * \return the optimal point location
   */
  OutputPointType Relocate(OutputQEType *iEdge);

private:
  SquaredEdgeLengthDecimationQuadEdgeMeshFilter(const Self &);
  void operator=(const Self &);
};
}

#include "itkSquaredEdgeLengthDecimationQuadEdgeMeshFilter.txx"
#endif

redpajama_set_name: RedPajamaGithub


text:
<?php

//error_reporting(E_ALL|E_STRICT);
//error_reporting(E_ALL);
//ini_set('display_errors', 'on');
ini_set('display_errors', 'off');

ini_set('include_path', ini_get('include_path') . PATH_SEPARATOR . '@@lib-path@@');
require_once "Zend/Loader.php";

Zend_Loader::loadClass('Zend_Controller_Front');

$front = Zend_Controller_Front::getInstance();
$front->SetControllerDirectory('@@controller-path@@');
$front->throwExceptions(true);

$front->dispatch();

?>


text:
package com.spring.data.jpa;

import org.hamcrest.CoreMatchers;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.data.jpa.repository.config.EnableJpaRepositories;
import org.springframework.test.context.junit4.SpringRunner;

import javax.annotation.PostConstruct;

import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;

import static org.hamcrest.core.Is.is;

@RunWith(SpringRunner.class)
@SpringBootTest
@EnableJpaRepositories
public class SpringDataJpaApplicationTests {

    @Autowired
    private CustomerRepository customerRepository;

    @PostConstruct
    public void setUp() {
        Customer michael = new Customer("Michael", "Doe", "Male");
        michael.addAddress(new Address("A2", "NewYork", "33221"));
        customerRepository.save(michael);
        customerRepository.save(new Customer("John", "Doe", "Male"));
        customerRepository.save(new Customer("Jenifer", "Roberts", "Female"));
    }

    @Test
    public void testCount() {
        long customers = this.customerRepository.count();
        Assert.assertThat(customers, is(3L));
    }

    @Test
    public void testFindAll() {
        Customer customer = new Customer("Michael", "Doe", "Male");
        customer.setId(1);
        Iterable<Customer> customers = this.customerRepository.findAll();
        Assert.assertThat(customers, CoreMatchers.hasItem(customer));
    }

    @Test
    public void testFindByLastName() {
        Iterable<Customer> roberts = this.customerRepository.findByLastName("Roberts");
        long size = roberts.spliterator().estimateSize();
        Assert.assertThat(size, is(1L));
        Assert.assertThat(roberts.iterator().next().getLastName(), is("Roberts"));
    }

    @Test
    public void testFindByZipCode() {
        Iterable<Customer> addressZipCode = this.customerRepository.findByAddressZipCode("33221");
        Assert.assertThat(addressZipCode.iterator().next().getAddress().iterator().next().getZipCode(),
                is("33221"));
    }
}


text:
namespace Magellan.Framework
{
    /// <summary>
    /// A base class for <see cref="Controller">controllers</see> that are executed asynchronously. An
    /// alternative to using this is to manually set the controller's <see cref="ActionInvoker"/> property
    /// to an instance of an <see cref="AsyncActionInvoker"/>, or use the
    /// <see cref="AsyncControllerFactory"/>.
    /// </summary>
    public class AsyncController : Controller
    {
        /// <summary>
        /// Initializes a new instance of the <see cref="AsyncController"/> class.
        /// </summary>
        public AsyncController()
        {
            ActionInvoker = new AsyncActionInvoker();
        }
    }
}


text:
<?php

/**
 * Test: Subject\Role->asAllowed()
 * @dataProvider? ../databases.ini
 */

use Tester\Assert;

require __DIR__ . '/../connect.inc.php'; // create $connection

$database = 'test_' . Nette\Utils\Random::generate(10, 'a-zA-Z');
$connect($database);

Nette\Database\Helpers::loadFromFile($connection, __DIR__ . "/../files/test1.sql");

$subject = new RM\Acl\Subject\Role($context);

/**
 * Role 'guest' has access to book:detail.
 * Role 'guest' has not access to book:detail '2001: A Space Odyssey'.
 */

$user = Mockery::mock('Nette\Security\User')
	->shouldReceive('getRoles')->andReturn(['guest'])
	->getMock();

Assert::same(NULL, $subject->isAllowed($user, 'book'));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail'));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail', 1));
Assert::same(FALSE, $subject->isAllowed($user, 'book', 'detail', 2));

Assert::same(NULL, $subject->isAllowed($user, 'book', 'publish'));
Assert::same(NULL, $subject->isAllowed($user, 'book', 'publish', 1));
Assert::same(NULL, $subject->isAllowed($user, 'book', 'publish', 2));

Assert::same(NULL, $subject->isAllowed($user, 'book', 'comment'));
Assert::same(NULL, $subject->isAllowed($user, 'book', 'comment', 1));
Assert::same(NULL, $subject->isAllowed($user, 'book', 'comment', 2));

Assert::same(NULL, $subject->isAllowed($user, 'book', 'undefined'));
Assert::same(NULL, $subject->isAllowed($user, 'undefined', 'undefined'));

/**
 * Role 'registred' has access to book:detail
 * Role 'registred' has access to book:comment
 */
$user = Mockery::mock('Nette\Security\User')
	->shouldReceive('getRoles')->andReturn(['registred'])
	->getMock();

Assert::same(NULL, $subject->isAllowed($user, 'book'));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail'));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail', 1));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail', 2));

Assert::same(NULL, $subject->isAllowed($user, 'book', 'publish'));
Assert::same(NULL, $subject->isAllowed($user, 'book', 'publish', 1));
Assert::same(NULL, $subject->isAllowed($user, 'book', 'publish', 2));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'comment'));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'comment', 1));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'comment', 2));

Assert::same(NULL, $subject->isAllowed($user, 'book', 'undefined'));
Assert::same(NULL, $subject->isAllowed($user, 'undefined', 'undefined'));

/**
 * Role 'author' has access to book:publish and inherit access from 'registred'.
 */
$user = Mockery::mock('Nette\Security\User')
	->shouldReceive('getRoles')->andReturn(['author'])
	->getMock();

Assert::same(NULL, $subject->isAllowed($user, 'book'));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail'));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail', 1));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail', 2));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'publish'));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'publish', 1));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'publish', 2));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'comment'));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'comment', 1));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'comment', 2));

Assert::same(NULL, $subject->isAllowed($user, 'book', 'undefined'));
Assert::same(NULL, $subject->isAllowed($user, 'undefined', 'undefined'));

/**
 * Role 'superadmin' has access to book:*.
 */
$user = Mockery::mock('Nette\Security\User')
	->shouldReceive('getRoles')->andReturn(['superadmin'])
	->getMock();

Assert::same(TRUE, $subject->isAllowed($user, 'book'));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail'));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail', 1));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'detail', 2));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'publish'));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'publish', 1));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'publish', 2));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'comment'));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'comment', 1));
Assert::same(TRUE, $subject->isAllowed($user, 'book', 'comment', 2));

Assert::same(TRUE, $subject->isAllowed($user, 'book', 'undefined'));
Assert::same(NULL, $subject->isAllowed($user, 'undefined', 'undefined'));

$disconnect($database);


text:
import operator
import unittest

from test import support

class Seq1:
    def __init__(self, lst):
        self.lst = lst
    def __len__(self):
        return len(self.lst)
    def __getitem__(self, i):
        return self.lst[i]
    def __add__(self, other):
        return self.lst + other.lst
    def __mul__(self, other):
        return self.lst * other
    def __rmul__(self, other):
        return other * self.lst

class Seq2(object):
    def __init__(self, lst):
        self.lst = lst
    def __len__(self):
        return len(self.lst)
    def __getitem__(self, i):
        return self.lst[i]
    def __add__(self, other):
        return self.lst + other.lst
    def __mul__(self, other):
        return self.lst * other
    def __rmul__(self, other):
        return other * self.lst

class OperatorTestCase(unittest.TestCase):
    def test_lt(self):
        self.assertRaises(TypeError, operator.lt)
        self.assertRaises(TypeError, operator.lt, 1j, 2j)
        self.assertFalse(operator.lt(1, 0))
        self.assertFalse(operator.lt(1, 0.0))
        self.assertFalse(operator.lt(1, 1))
        self.assertFalse(operator.lt(1, 1.0))
        self.assertTrue(operator.lt(1, 2))
        self.assertTrue(operator.lt(1, 2.0))

    def test_le(self):
        self.assertRaises(TypeError, operator.le)
        self.assertRaises(TypeError, operator.le, 1j, 2j)
        self.assertFalse(operator.le(1, 0))
        self.assertFalse(operator.le(1, 0.0))
        self.assertTrue(operator.le(1, 1))
        self.assertTrue(operator.le(1, 1.0))
        self.assertTrue(operator.le(1, 2))
        self.assertTrue(operator.le(1, 2.0))

    def test_eq(self):
        class C(object):
            def __eq__(self, other):
                raise SyntaxError
        self.assertRaises(TypeError, operator.eq)
        self.assertRaises(SyntaxError, operator.eq, C(), C())
        self.assertFalse(operator.eq(1, 0))
        self.assertFalse(operator.eq(1, 0.0))
        self.assertTrue(operator.eq(1, 1))
        self.assertTrue(operator.eq(1, 1.0))
        self.assertFalse(operator.eq(1, 2))
        self.assertFalse(operator.eq(1, 2.0))

    def test_ne(self):
        class C(object):
            def __ne__(self, other):
                raise SyntaxError
        self.assertRaises(TypeError, operator.ne)
        self.assertRaises(SyntaxError, operator.ne, C(), C())
        self.assertTrue(operator.ne(1, 0))
        self.assertTrue(operator.ne(1, 0.0))
        self.assertFalse(operator.ne(1, 1))
        self.assertFalse(operator.ne(1, 1.0))
        self.assertTrue(operator.ne(1, 2))
        self.assertTrue(operator.ne(1, 2.0))

    def test_ge(self):
        self.assertRaises(TypeError, operator.ge)
        self.assertRaises(TypeError, operator.ge, 1j, 2j)
        self.assertTrue(operator.ge(1, 0))
        self.assertTrue(operator.ge(1, 0.0))
        self.assertTrue(operator.ge(1, 1))
        self.assertTrue(operator.ge(1, 1.0))
        self.assertFalse(operator.ge(1, 2))
        self.assertFalse(operator.ge(1, 2.0))

    def test_gt(self):
        self.assertRaises(TypeError, operator.gt)
        self.assertRaises(TypeError, operator.gt, 1j, 2j)
        self.assertTrue(operator.gt(1, 0))
        self.assertTrue(operator.gt(1, 0.0))
        self.assertFalse(operator.gt(1, 1))
        self.assertFalse(operator.gt(1, 1.0))
        self.assertFalse(operator.gt(1, 2))
        self.assertFalse(operator.gt(1, 2.0))

    def test_abs(self):
        self.assertRaises(TypeError, operator.abs)
        self.assertRaises(TypeError, operator.abs, None)
        self.assertEqual(operator.abs(-1), 1)
        self.assertEqual(operator.abs(1), 1)

    def test_add(self):
        self.assertRaises(TypeError, operator.add)
        self.assertRaises(TypeError, operator.add, None, None)
        self.assertTrue(operator.add(3, 4) == 7)

    def test_bitwise_and(self):
        self.assertRaises(TypeError, operator.and_)
        self.assertRaises(TypeError, operator.and_, None, None)
        self.assertTrue(operator.and_(0xf, 0xa) == 0xa)

    def test_concat(self):
        self.assertRaises(TypeError, operator.concat)
        self.assertRaises(TypeError, operator.concat, None, None)
        self.assertTrue(operator.concat('py', 'thon') == 'python')
        self.assertTrue(operator.concat([1, 2], [3, 4]) == [1, 2, 3, 4])
        self.assertTrue(operator.concat(Seq1([5, 6]), Seq1([7])) == [5, 6, 7])
        self.assertTrue(operator.concat(Seq2([5, 6]), Seq2([7])) == [5, 6, 7])
        self.assertRaises(TypeError, operator.concat, 13, 29)

    def test_countOf(self):
        self.assertRaises(TypeError, operator.countOf)
        self.assertRaises(TypeError, operator.countOf, None, None)
        self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 3) == 1)
        self.assertTrue(operator.countOf([1, 2, 1, 3, 1, 4], 5) == 0)

    def test_delitem(self):
        a = [4, 3, 2, 1]
        self.assertRaises(TypeError, operator.delitem, a)
        self.assertRaises(TypeError, operator.delitem, a, None)
        self.assertTrue(operator.delitem(a, 1) is None)
        self.assertTrue(a == [4, 2, 1])

    def test_floordiv(self):
        self.assertRaises(TypeError, operator.floordiv, 5)
        self.assertRaises(TypeError, operator.floordiv, None, None)
        self.assertTrue(operator.floordiv(5, 2) == 2)

    def test_truediv(self):
        self.assertRaises(TypeError, operator.truediv, 5)
        self.assertRaises(TypeError, operator.truediv, None, None)
        self.assertTrue(operator.truediv(5, 2) == 2.5)

    def test_getitem(self):
        a = range(10)
        self.assertRaises(TypeError, operator.getitem)
        self.assertRaises(TypeError, operator.getitem, a, None)
        self.assertTrue(operator.getitem(a, 2) == 2)

    def test_indexOf(self):
        self.assertRaises(TypeError, operator.indexOf)
        self.assertRaises(TypeError, operator.indexOf, None, None)
        self.assertTrue(operator.indexOf([4, 3, 2, 1], 3) == 1)
        self.assertRaises(ValueError, operator.indexOf, [4, 3, 2, 1], 0)

    def test_invert(self):
        self.assertRaises(TypeError, operator.invert)
        self.assertRaises(TypeError, operator.invert, None)
        self.assertEqual(operator.inv(4), -5)

    def test_lshift(self):
        self.assertRaises(TypeError, operator.lshift)
        self.assertRaises(TypeError, operator.lshift, None, 42)
        self.assertTrue(operator.lshift(5, 1) == 10)
        self.assertTrue(operator.lshift(5, 0) == 5)
        self.assertRaises(ValueError, operator.lshift, 2, -1)

    def test_mod(self):
        self.assertRaises(TypeError, operator.mod)
        self.assertRaises(TypeError, operator.mod, None, 42)
        self.assertTrue(operator.mod(5, 2) == 1)

    def test_mul(self):
        self.assertRaises(TypeError, operator.mul)
        self.assertRaises(TypeError, operator.mul, None, None)
        self.assertTrue(operator.mul(5, 2) == 10)

    def test_neg(self):
        self.assertRaises(TypeError, operator.neg)
        self.assertRaises(TypeError, operator.neg, None)
        self.assertEqual(operator.neg(5), -5)
        self.assertEqual(operator.neg(-5), 5)
        self.assertEqual(operator.neg(0), 0)
        self.assertEqual(operator.neg(-0), 0)

    def test_bitwise_or(self):
        self.assertRaises(TypeError, operator.or_)
        self.assertRaises(TypeError, operator.or_, None, None)
        self.assertTrue(operator.or_(0xa, 0x5) == 0xf)

    def test_pos(self):
        self.assertRaises(TypeError, operator.pos)
        self.assertRaises(TypeError, operator.pos, None)
        self.assertEqual(operator.pos(5), 5)
        self.assertEqual(operator.pos(-5), -5)
        self.assertEqual(operator.pos(0), 0)
        self.assertEqual(operator.pos(-0), 0)

    def test_pow(self):
        self.assertRaises(TypeError, operator.pow)
        self.assertRaises(TypeError, operator.pow, None, None)
        self.assertEqual(operator.pow(3,5), 3**5)
        self.assertEqual(operator.__pow__(3,5), 3**5)
        self.assertRaises(TypeError, operator.pow, 1)
        self.assertRaises(TypeError, operator.pow, 1, 2, 3)

    def test_rshift(self):
        self.assertRaises(TypeError, operator.rshift)
        self.assertRaises(TypeError, operator.rshift, None, 42)
        self.assertTrue(operator.rshift(5, 1) == 2)
        self.assertTrue(operator.rshift(5, 0) == 5)
        self.assertRaises(ValueError, operator.rshift, 2, -1)

    def test_contains(self):
        self.assertRaises(TypeError, operator.contains)
        self.assertRaises(TypeError, operator.contains, None, None)
        self.assertTrue(operator.contains(range(4), 2))
        self.assertFalse(operator.contains(range(4), 5))

    def test_setitem(self):
        a = list(range(3))
        self.assertRaises(TypeError, operator.setitem, a)
        self.assertRaises(TypeError, operator.setitem, a, None, None)
        self.assertTrue(operator.setitem(a, 0, 2) is None)
        self.assertTrue(a == [2, 1, 2])
        self.assertRaises(IndexError, operator.setitem, a, 4, 2)

    def test_sub(self):
        self.assertRaises(TypeError, operator.sub)
        self.assertRaises(TypeError, operator.sub, None, None)
        self.assertTrue(operator.sub(5, 2) == 3)

    def test_truth(self):
        class C(object):
            def __bool__(self):
                raise SyntaxError
        self.assertRaises(TypeError, operator.truth)
        self.assertRaises(SyntaxError, operator.truth, C())
        self.assertTrue(operator.truth(5))
        self.assertTrue(operator.truth([0]))
        self.assertFalse(operator.truth(0))
        self.assertFalse(operator.truth([]))

    def test_bitwise_xor(self):
        self.assertRaises(TypeError, operator.xor)
        self.assertRaises(TypeError, operator.xor, None, None)
        self.assertTrue(operator.xor(0xb, 0xc) == 0x7)

    def test_is(self):
        a = b = 'xyzpdq'
        c = a[:3] + b[3:]
        self.assertRaises(TypeError, operator.is_)
        self.assertTrue(operator.is_(a, b))
        self.assertFalse(operator.is_(a,c))

    def test_is_not(self):
        a = b = 'xyzpdq'
        c = a[:3] + b[3:]
        self.assertRaises(TypeError, operator.is_not)
        self.assertFalse(operator.is_not(a, b))
        self.assertTrue(operator.is_not(a,c))

    def test_attrgetter(self):
        class A:
            pass
        a = A()
        a.name = 'arthur'
        f = operator.attrgetter('name')
        self.assertEqual(f(a), 'arthur')
        f = operator.attrgetter('rank')
        self.assertRaises(AttributeError, f, a)
        self.assertRaises(TypeError, operator.attrgetter, 2)
        self.assertRaises(TypeError, operator.attrgetter)

        # multiple gets
        record = A()
        record.x = 'X'
        record.y = 'Y'
        record.z = 'Z'
        self.assertEqual(operator.attrgetter('x','z','y')(record), ('X', 'Z', 'Y'))
        self.assertRaises(TypeError, operator.attrgetter, ('x', (), 'y'))

        class C(object):
            def __getattr__(self, name):
                raise SyntaxError
        self.assertRaises(SyntaxError, operator.attrgetter('foo'), C())

        # recursive gets
        a = A()
        a.name = 'arthur'
        a.child = A()
        a.child.name = 'thomas'
        f = operator.attrgetter('child.name')
        self.assertEqual(f(a), 'thomas')
        self.assertRaises(AttributeError, f, a.child)
        f = operator.attrgetter('name', 'child.name')
        self.assertEqual(f(a), ('arthur', 'thomas'))
        f = operator.attrgetter('name', 'child.name', 'child.child.name')
        self.assertRaises(AttributeError, f, a)
        f = operator.attrgetter('child.')
        self.assertRaises(AttributeError, f, a)
        f = operator.attrgetter('.child')
        self.assertRaises(AttributeError, f, a)

        a.child.child = A()
        a.child.child.name = 'johnson'
        f = operator.attrgetter('child.child.name')
        self.assertEqual(f(a), 'johnson')
        f = operator.attrgetter('name', 'child.name', 'child.child.name')
        self.assertEqual(f(a), ('arthur', 'thomas', 'johnson'))

    def test_itemgetter(self):
        a = 'ABCDE'
        f = operator.itemgetter(2)
        self.assertEqual(f(a), 'C')
        f = operator.itemgetter(10)
        self.assertRaises(IndexError, f, a)

        class C(object):
            def __getitem__(self, name):
                raise SyntaxError
        self.assertRaises(SyntaxError, operator.itemgetter(42), C())

        f = operator.itemgetter('name')
        self.assertRaises(TypeError, f, a)
        self.assertRaises(TypeError, operator.itemgetter)

        d = dict(key='val')
        f = operator.itemgetter('key')
        self.assertEqual(f(d), 'val')
        f = operator.itemgetter('nonkey')
        self.assertRaises(KeyError, f, d)

        # example used in the docs
        inventory = [('apple', 3), ('banana', 2), ('pear', 5), ('orange', 1)]
        getcount = operator.itemgetter(1)
        self.assertEqual(list(map(getcount, inventory)), [3, 2, 5, 1])
        self.assertEqual(sorted(inventory, key=getcount),
            [('orange', 1), ('banana', 2), ('apple', 3), ('pear', 5)])

        # multiple gets
        data = list(map(str, range(20)))
        self.assertEqual(operator.itemgetter(2,10,5)(data), ('2', '10', '5'))
        self.assertRaises(TypeError, operator.itemgetter(2, 'x', 5), data)

    def test_methodcaller(self):
        self.assertRaises(TypeError, operator.methodcaller)
        class A:
            def foo(self, *args, **kwds):
                return args[0] + args[1]
            def bar(self, f=42):
                return f
        a = A()
        f = operator.methodcaller('foo')
        self.assertRaises(IndexError, f, a)
        f = operator.methodcaller('foo', 1, 2)
        self.assertEqual(f(a), 3)
        f = operator.methodcaller('bar')
        self.assertEqual(f(a), 42)
        self.assertRaises(TypeError, f, a, a)
        f = operator.methodcaller('bar', f=5)
        self.assertEqual(f(a), 5)

    def test_inplace(self):
        class C(object):
            def __iadd__     (self, other): return "iadd"
            def __iand__     (self, other): return "iand"
            def __ifloordiv__(self, other): return "ifloordiv"
            def __ilshift__  (self, other): return "ilshift"
            def __imod__     (self, other): return "imod"
            def __imul__     (self, other): return "imul"
            def __ior__      (self, other): return "ior"
            def __ipow__     (self, other): return "ipow"
            def __irshift__  (self, other): return "irshift"
            def __isub__     (self, other): return "isub"
            def __itruediv__ (self, other): return "itruediv"
            def __ixor__     (self, other): return "ixor"
            def __getitem__(self, other): return 5  # so that C is a sequence
        c = C()
        self.assertEqual(operator.iadd     (c, 5), "iadd")
        self.assertEqual(operator.iand     (c, 5), "iand")
        self.assertEqual(operator.ifloordiv(c, 5), "ifloordiv")
        self.assertEqual(operator.ilshift  (c, 5), "ilshift")
        self.assertEqual(operator.imod     (c, 5), "imod")
        self.assertEqual(operator.imul     (c, 5), "imul")
        self.assertEqual(operator.ior      (c, 5), "ior")
        self.assertEqual(operator.ipow     (c, 5), "ipow")
        self.assertEqual(operator.irshift  (c, 5), "irshift")
        self.assertEqual(operator.isub     (c, 5), "isub")
        self.assertEqual(operator.itruediv (c, 5), "itruediv")
        self.assertEqual(operator.ixor     (c, 5), "ixor")
        self.assertEqual(operator.iconcat  (c, c), "iadd")
        self.assertEqual(operator.__iadd__     (c, 5), "iadd")
        self.assertEqual(operator.__iand__     (c, 5), "iand")
        self.assertEqual(operator.__ifloordiv__(c, 5), "ifloordiv")
        self.assertEqual(operator.__ilshift__  (c, 5), "ilshift")
        self.assertEqual(operator.__imod__     (c, 5), "imod")
        self.assertEqual(operator.__imul__     (c, 5), "imul")
        self.assertEqual(operator.__ior__      (c, 5), "ior")
        self.assertEqual(operator.__ipow__     (c, 5), "ipow")
        self.assertEqual(operator.__irshift__  (c, 5), "irshift")
        self.assertEqual(operator.__isub__     (c, 5), "isub")
        self.assertEqual(operator.__itruediv__ (c, 5), "itruediv")
        self.assertEqual(operator.__ixor__     (c, 5), "ixor")
        self.assertEqual(operator.__iconcat__  (c, c), "iadd")

def test_main(verbose=None):
    import sys
    test_classes = (
        OperatorTestCase,
    )

    support.run_unittest(*test_classes)

    # verify reference counting
    if verbose and hasattr(sys, "gettotalrefcount"):
        import gc
        counts = [None] * 5
        for i in range(len(counts)):
            support.run_unittest(*test_classes)
            gc.collect()
            counts[i] = sys.gettotalrefcount()
        print(counts)

if __name__ == "__main__":
    test_main(verbose=True)


text:
// Licensed to the Apache Software Foundation (ASF) under one
// or more contributor license agreements.  See the NOTICE file
// distributed with this work for additional information
// regarding copyright ownership.  The ASF licenses this file
// to you under the Apache License, Version 2.0 (the
// "License"); you may not use this file except in compliance
// with the License.  You may obtain a copy of the License at
//
//   http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing,
// software distributed under the License is distributed on an
// "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
// KIND, either express or implied.  See the License for the
// specific language governing permissions and limitations
// under the License.
package rdpclient.ntlmssp.asn1;

import common.asn1.OctetString;
import common.asn1.Sequence;
import common.asn1.Tag;

/**
 * The NegoData structure contains the SPNEGO messages, as specified in
 * [MS-SPNG] section 2.
 *
 *

 * NegoData ::= SEQUENCE OF SEQUENCE {
 *   negoToken     [0] OCTET STRING
 * }
 *

 *
 * If we write NegoItem as
 *
 *

 * NegoItem ::= SEQUENCE {
 *   negoToken     [0] OCTET STRING
 * }
 *

 *
 * then NegoData can be written as
 *
 *

 * NegoData ::= SEQUENCE OF NegoItem
 *

 *
 *

 *
negoToken: One or more SPNEGO tokens, as specified in [MS-SPNG].
 *

 *
 * @see http://msdn.microsoft.com/en-us/library/cc226781.aspx
 */
public class NegoItem extends Sequence {

    public OctetString negoToken = new OctetString("negoToken") {
        {
            explicit = true;
            tagClass = CONTEXT_CLASS;
            tagNumber = 0;
        }
    };

    public NegoItem(String name) {
        super(name);
        tags = new Tag[] {negoToken};
    }

    @Override
    public Tag deepCopy(String suffix) {
        return new NegoItem(name + suffix).copyFrom(this);
    }

}


text:
package org.apache.cassandra.streaming.management;

import java.util.*;
import javax.management.openmbean.*;

import com.google.common.base.Function;
import com.google.common.base.Throwables;
import com.google.common.collect.Iterables;
import com.google.common.collect.Lists;
import com.google.common.collect.Sets;

import org.apache.cassandra.streaming.SessionInfo;
import org.apache.cassandra.streaming.StreamState;

/**
 */
public class StreamStateCompositeData
{
    private static final String[] ITEM_NAMES = new String[]{"planId", "description", "sessions",
                                                            "currentRxBytes", "totalRxBytes", "rxPercentage",
                                                            "currentTxBytes", "totalTxBytes", "txPercentage"};
    private static final String[] ITEM_DESCS = new String[]{"Plan ID of this stream",
                                                            "Stream plan description",
                                                            "Active stream sessions",
                                                            "Number of bytes received across all streams",
                                                            "Total bytes available to receive across all streams",
                                                            "Percentage received across all streams",
                                                            "Number of bytes sent across all streams",
                                                            "Total bytes available to send across all streams",
                                                            "Percentage sent across all streams"};
    private static final OpenType<?>[] ITEM_TYPES;

    public static final CompositeType COMPOSITE_TYPE;
    static
    {
        try
        {
            ITEM_TYPES = new OpenType[]{SimpleType.STRING,
                                         SimpleType.STRING,
                                         ArrayType.getArrayType(SessionInfoCompositeData.COMPOSITE_TYPE),
                                         SimpleType.LONG, SimpleType.LONG, SimpleType.DOUBLE,
                                         SimpleType.LONG, SimpleType.LONG, SimpleType.DOUBLE};
            COMPOSITE_TYPE = new CompositeType(StreamState.class.getName(),
                                            "StreamState",
                                            ITEM_NAMES,
                                            ITEM_DESCS,
                                            ITEM_TYPES);
        }
        catch (OpenDataException e)
        {
            throw Throwables.propagate(e);
        }
    }

    public static CompositeData toCompositeData(final StreamState streamState)
    {
        Map<String, Object> valueMap = new HashMap<>();
        valueMap.put(ITEM_NAMES[0], streamState.planId.toString());
        valueMap.put(ITEM_NAMES[1], streamState.description);

        CompositeData[] sessions = new CompositeData[streamState.sessions.size()];
        Lists.newArrayList(Iterables.transform(streamState.sessions, new Function<SessionInfo, CompositeData>()
        {
            public CompositeData apply(SessionInfo input)
            {
                return SessionInfoCompositeData.toCompositeData(streamState.planId, input);
            }
        })).toArray(sessions);
        valueMap.put(ITEM_NAMES[2], sessions);

        long currentRxBytes = 0;
        long totalRxBytes = 0;
        long currentTxBytes = 0;
        long totalTxBytes = 0;
        for (SessionInfo sessInfo : streamState.sessions)
        {
            currentRxBytes += sessInfo.getTotalSizeReceived();
            totalRxBytes += sessInfo.getTotalSizeToReceive();
            currentTxBytes += sessInfo.getTotalSizeSent();
            totalTxBytes += sessInfo.getTotalSizeToSend();
        }
        double rxPercentage = (totalRxBytes == 0 ? 100L : currentRxBytes * 100L / totalRxBytes);
        double txPercentage = (totalTxBytes == 0 ? 100L : currentTxBytes * 100L / totalTxBytes);

        valueMap.put(ITEM_NAMES[3], currentRxBytes);
        valueMap.put(ITEM_NAMES[4], totalRxBytes);
        valueMap.put(ITEM_NAMES[5], rxPercentage);
        valueMap.put(ITEM_NAMES[6], currentTxBytes);
        valueMap.put(ITEM_NAMES[7], totalTxBytes);
        valueMap.put(ITEM_NAMES[8], txPercentage);

        try
        {
            return new CompositeDataSupport(COMPOSITE_TYPE, valueMap);
        }
        catch (OpenDataException e)
        {
            throw Throwables.propagate(e);
        }
    }

    public static StreamState fromCompositeData(CompositeData cd)
    {
        assert cd.getCompositeType().equals(COMPOSITE_TYPE);
        Object[] values = cd.getAll(ITEM_NAMES);
        UUID planId = UUID.fromString((String) values[0]);
        String description = (String) values[1];
        Set<SessionInfo> sessions = Sets.newHashSet(Iterables.transform(Arrays.asList((CompositeData[]) values[2]),
                                                                        new Function<CompositeData, SessionInfo>()
                                                                        {
                                                                            public SessionInfo apply(CompositeData input)
                                                                            {
                                                                                return SessionInfoCompositeData.fromCompositeData(input);
                                                                            }
                                                                        }));
        return new StreamState(planId, description, sessions);
    }
}


text:
'use strict';

var config = require('../config/config');

function additionalRequiredData(keys, movies, type) {

    var data = {};

    data[type] = movies;

    for (var key in keys) {
        if (keys.hasOwnProperty(key)) {
            keys[key] = '' + keys[key] + '';
            data.name = addKeywords(config[type][key].name, keys)
        }
    }

    return data;

}

/* Required data on index page:
 - protocol
 - domain
 - email
 - urls
 - social
 - code
 - title
 - description
 - keywords
 - schema
 */

function indexRequiredData() {

    var data = {};

    data.protocol    = config.protocol;
    data.domain      = config.domain;
    data.email       = config.email;
    data.urls        = config.urls;
    data.social      = config.social;
    data.code        = changeCode(config.code);

    data.title       = addKeywords(config.titles.index);
    data.description = addKeywords(config.descriptions.index);
    data.keywords    = addKeywords(config.keywords.index);
    data.schema      = (config.schema) ? generalSchemaData(data) : {};

    return data;

}

/* Required data on movie page:
 - protocol
 - domain
 - email
 - urls
 - disqus
 - social
 - code
 - abuse
 - title
 - description
 - keywords
 - schema
 */

function movieRequiredData(key, keys, movies) {

    var data = {};

    data.protocol    = config.protocol;
    data.domain      = config.domain;
    data.email       = config.email;
    data.urls        = config.urls;
    data.disqus      = config.disqus;
    data.social      = config.social;
    data.abuse       = config.abuse;
    data.code        = changeCode(config.code);

    data.title       = addKeywords(config.titles.movie[key], keys);
    data.description = addKeywords(config.descriptions.movie[key], keys);
    data.keywords    = addKeywords(config.keywords.movie[key], keys);
    data.schema      = (config.schema) ? movieSchemaData(keys, movies) : {};

    return data;

}

/* Required data on category page:
 - protocol
 - domain
 - email
 - urls
 - social
 - code
 - url
 - sort
 - page
 - title
 - description
 - keywords
 - schema
 */

function categoryRequiredData(keys, sort, page, movies) {

    var data = {};

    data.protocol = config.protocol;
    data.domain   = config.domain;
    data.email    = config.email;
    data.urls     = config.urls;
    data.social   = config.social;
    data.code     = changeCode(config.code);

    for (var key in keys) {
        if (keys.hasOwnProperty(key)) {

            keys['sort'] = (config.sorting.default != sort)
                ? config.titles.sort[sort] || ''
                : '';
            keys['page'] = (page != 1)
                ? config.titles.num.replace('[num]', page)
                : '';

            data.title       = addKeywords(config.titles[key], keys);
            data.description = addKeywords(config.descriptions[key], keys);
            data.keywords    = addKeywords(config.keywords[key], keys);
            data.url         = urlData(config.urls[key], keys[key]);
            data.sort        = sortUrlData(data.url, sort);
            data.page        = {
                "description" : (config.sorting.default == sort && page == 1) ? 1 : 0,
                "current"     : page,
                "prev"        : pageUrlData(data.url, sort, page, movies.length, 'prev'),
                "next"        : pageUrlData(data.url, sort, page, movies.length, 'next')
            };

        }
    }

    data.schema = (config.schema) ? categorySchemaData(data, movies) : {};

    return data;

}

/* Required data on categories page:
 - protocol
 - domain
 - email
 - urls
 - social
 - code
 - url
 - title
 - description
 - keywords
 - schema
 */

function categoriesRequiredData(key) {

    var data = {};

    var type = {
        "year"     : "years",
        "genre"    : "genres",
        "actor"    : "actors",
        "country"  : "countries",
        "director" : "directors"
    };

    data.protocol    = config.protocol;
    data.domain      = config.domain;
    data.email       = config.email;
    data.urls        = config.urls;
    data.social      = config.social;
    data.code        = changeCode(config.code);
    data.url         = categoryUrl(key);

    data.title       = addKeywords(config.titles[type[key]]);
    data.description = addKeywords(config.descriptions[type[key]]);
    data.keywords    = addKeywords(config.keywords[type[key]]);
    data.schema      = (config.schema) ? generalSchemaData(data) : {};

    return data;

}

function urlData(attribute, query) {

    return config.protocol + config.domain + '/' + attribute + '/' + encodeURIComponent(query);

}

function categoryUrl(key) {

    return config.protocol + config.domain + '/' + config.urls[key];

}

function sortUrlData(url, sort) {

    var sortingUp = [
        'kinopoisk-rating-up',
        'imdb-rating-up',
        'kinopoisk-vote-up',
        'imdb-vote-up',
        'year-up',
        'premiere-up'
    ];

    var sortingDown = {
        "kinopoisk-rating-down" : sortingUp[0],
        "imdb-rating-down"      : sortingUp[1],
        "kinopoisk-vote-down"   : sortingUp[2],
        "imdb-vote-down"        : sortingUp[3],
        "year-down"             : sortingUp[4],
        "premiere-down"         : sortingUp[5]
    };

    return sortingUp.map(function(s) {

        var a = false;

        if (sort == s) {
            s = sort.replace('up','down');
            a = 'up';
        }
        else if (sortingDown[sort] == s) {
            a = 'down';
        }

        return {
            "name"   : config.sorting[s],
            "url"    : url + '?sort=' + s,
            "active" : a
        }

    });

}

function pageUrlData(url, sort, page, count, type) {

    if (type == 'prev') {
        return (page - 1) ? url + '/' + (page - 1) + '?sort=' + sort : '';
    }
    else {
        return (count == config.counts.category) ? url + '/' + (page + 1) + '?sort=' + sort : '';
    }

}

function addKeywords(text, keywords) {

    var dflt = true;

    text = text.replace(/ /g,' ');

    if (keywords) {
        for (var key in keywords) {
            if (keywords.hasOwnProperty(key)) {

                var keyRegExp = ('' + key).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');
                var keywordRegExp = ('' + keywords[key]).replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');

                var allSpecific = new RegExp('(\\s*\\(\\s*' + keywordRegExp + '\\s*\\)\\s*\\{(.*?)\\}\\s*)', 'gi');
                var match = allSpecific.exec(text);
                if (match) {dflt = false;}
                text = text.replace(allSpecific, ' $2 ');

                var allKeys = new RegExp('\\[' + keyRegExp + '\\]', 'g');
                text = text.replace(allKeys, keywords[key]);

            }
        }
    }

    if (dflt) {
        var defaultSpecific = new RegExp('(\\s*\\(\\s*default\\s*\\)\\s*\\{(.*?)\\}\\s*)', 'gi');
        text = text.replace(defaultSpecific, ' $2 ');
    }

    var allSpecifics = new RegExp('(\\s*\\(.*?\\)\\s*\\{(.*?)\\}\\s*)', 'gi');
    text = text.replace(allSpecifics, ' ');

    text = text.replace(/ /gi, ' ');
    text = text.replace(/\s+/g, ' ');
    text = text.replace(/(^\s*)|(\s*)$/g, '');

    while (true) {

        var p = new RegExp('\\[(.*?)\\]', 'g');
        var parts = p.exec(text);

        if (parts) {
            var search = parts[0];
            var part = parts[1].split('|');
            var replace = part[Math.floor(Math.random() * part.length)];
            text = text.replace(search, replace);
        }
        else {

            break;

        }

    }

    return text;

}

function movieSchemaData(movie, movies) {

    if (!movie || !movies) return [];

    var result = [];

    for (var category in movies) {
        if (movies.hasOwnProperty(category)) {

            movies[category].forEach(function(data) {

                var schemaItemList = {};
                schemaItemList['@context'] = 'http://schema.org';
                schemaItemList['@type'] = 'ItemList';
                schemaItemList['name'] = data.name.replace(/<\/?[^>]+(>|$)/g, '');
                schemaItemList['numberOfItems'] = data.related.length;
                schemaItemList['itemListOrder'] = 'Descending';
                schemaItemList['itemListElement'] = [];

                data.related.forEach(function(m, key) {

                    schemaItemList['itemListElement'].push({
                        "@type": "ListItem",
                        "position": key+1,
                        "item": schemaMovie(m)
                    });

                });

                result.push(schemaItemList);

            });

        }
    }

    var schemaBreadcrumbList = {};

    schemaBreadcrumbList['@context'] = 'http://schema.org';
    schemaBreadcrumbList['@type'] = 'BreadcrumbList';
    schemaBreadcrumbList['itemListElement'] = [];

    schemaBreadcrumbList['itemListElement'].push({
        "@type": "ListItem",
        "position": 1,
        "item": {
            "@id": "/",
            "name": "Главная",
            "url":  config.protocol + config.domain
        }
    });

    schemaBreadcrumbList['itemListElement'].push({
        "@type": "ListItem",
        "position": 2,
        "item": {
            "@id": "/" + encodeURIComponent(config.urls.genre) + "/" + encodeURIComponent(movie.genre),
            "name": movie.genre,
            "url": config.protocol + config.domain + "/" + encodeURIComponent(config.urls.genre) + "/" + encodeURIComponent(movie.genre)
        }
    });

    schemaBreadcrumbList['itemListElement'].push({
        "@type": "ListItem",
        "position": 3,
        "item": {
            "@id": movie.url,
            "name": movie.title,
            "url": movie.url
        }
    });

    result.push(schemaMovie(movie));
    result.push(schemaBreadcrumbList);

    return result;

}

function schemaMovie(movie) {

    var schemaMovie = {};

    schemaMovie['@context'] = 'http://schema.org';
    schemaMovie['@type'] = 'Movie';
    schemaMovie['name'] = movie.title_ru;
    schemaMovie['alternativeHeadline'] = movie.title_en;
    schemaMovie['description'] = movie.description;
    schemaMovie['image'] = movie.poster;
    schemaMovie['sameAs'] =  movie.url;
    schemaMovie['url'] =  movie.url;
    schemaMovie['actor'] = [];
    schemaMovie['director'] = [];
    schemaMovie['genre'] = [];
    schemaMovie['aggregateRating'] = (movie.kp_rating || movie.imdb_rating)
        ? {
            "@type": "AggregateRating",
            "bestRating": 10,
            "ratingCount": movie.kp_vote + movie.imdb_vote,
            "ratingValue": Math.round( ( ((movie.kp_rating || movie.imdb_rating)/10 + (movie.imdb_rating || movie.kp_rating)/10) / 2) * 10 ) / 10
        }
        : null;

    if (movie.actors_arr) {
        movie.actors_arr.forEach(function (actor) {
            schemaMovie['actor'].push({
                "@type": "Person",
                "name": actor,
                "sameAs": config.protocol + config.domain + "/" + encodeURIComponent(config.urls.actor) + "/" + encodeURIComponent(actor)
            });
        });
    }

    if (movie.directors_arr) {
        movie.directors_arr.forEach(function (director) {
            schemaMovie['director'].push({
                "@type": "Person",
                "name": director,
                "sameAs": config.protocol + config.domain + "/" + encodeURIComponent(config.urls.director) + "/" + encodeURIComponent(director)
            });
        });
    }

    if (movie.genres_arr) {
        movie.genres_arr.forEach(function (genre) {
            schemaMovie['genre'].push(encodeURIComponent(genre));
        });
    }

    return schemaMovie;

}

function categorySchemaData(data, movies) {

    var result = [];

    var schemaItemList = {};
    var schemaBreadcrumbList = {};

    schemaItemList['@context'] = 'http://schema.org';
    schemaItemList['@type'] = 'ItemList';
    schemaItemList['name'] = data.title;
    schemaItemList['numberOfItems'] = movies.length;
    schemaItemList['itemListOrder'] = 'Descending';
    schemaItemList['itemListElement'] = [];

    movies.forEach(function(movie, key) {

        schemaItemList['itemListElement'].push({
            "@type": "ListItem",
            "position": key+1,
            "item": schemaMovie(movie)
        });

    });

    schemaBreadcrumbList['@context'] = 'http://schema.org';
    schemaBreadcrumbList['@type'] = 'BreadcrumbList';
    schemaBreadcrumbList['itemListElement'] = [];

    schemaBreadcrumbList['itemListElement'].push({
        "@type": "ListItem",
        "position": 1,
        "item": {
            "@id": "/",
            "name": "Главная",
            "url": config.protocol + config.domain
        }
    });

    schemaBreadcrumbList['itemListElement'].push({
        "@type": "ListItem",
        "position": 2,
        "item": {
            "@id": data.url,
            "name": data.title,
            "url": data.url
        }
    });

    result.push(schemaItemList);
    result.push(schemaBreadcrumbList);

    return result;

}

function generalSchemaData(data) {

    var schemaWebSite = {};

    schemaWebSite['@context'] = 'http://schema.org';
    schemaWebSite['@type'] = 'WebSite';
    schemaWebSite['name'] = data.title;
    schemaWebSite['url'] = config.protocol + config.domain;
    schemaWebSite['potentialAction'] = {
        "@type": "SearchAction",
        "target": config.protocol + config.domain + "/" + config.urls.search + "/title?&q={query}",
        "query-input": "required name=query"
    };

    return schemaWebSite;

}

function changeCode(code) {

    for (var key in code) {
        if (code.hasOwnProperty(key)) {
            code[key] = code[key].replace(/ /gi,'');
        }
    }

    return code;

}

module.exports = {
    "index"      : indexRequiredData,
    "movie"      : movieRequiredData,
    "category"   : categoryRequiredData,
    "categories" : categoriesRequiredData,
    "additional" : additionalRequiredData
};


text:
from django.conf.urls import patterns, url

urlpatterns = patterns('website.views',
                       url(r'^buildings/$', 'buildingAPIViews.buildingList'),
                       url(r'^buildings/(?P<pk>[0-9]+)$', 'buildingAPIViews.buildingDetail'),
                       url(r'^buildings/(?P<bc>.+)$', 'buildingAPIViews.buildingDetail'),
                       url(r'^collections/$', 'collectionAPIViews.collectionList'),
                       url(r'^collections/(?P<pk>[0-9]+)$', 'collectionAPIViews.collectionDetail'),
                       url(r'^collections/(?P<cn>.+)$', 'collectionAPIViews.collectionDetail'),
                       url(r'^labels/$', 'labelAPIViews.labelList'),
                       url(r'^labels/(?P<pk>[0-9]+)$', 'labelAPIViews.labelDetail'),
                       url(r'^labels/(?P<ln>.+)$', 'labelAPIViews.labelDetail'),
                       url(r'^labelsNotCategories/$', 'views.labelsNotCategories'),
                       url(r'^locations/$', 'locationAPIViews.locationList'),
                       url(r'^locations/(?P<pk>[0-9]+)$', 'locationAPIViews.locationDetail'),
                       url(r'^models/$', 'itemModelAPIViews.itemModelList'),
                       url(r'^models/(?P<pk>[0-9]+)$', 'itemModelAPIViews.itemModelDetail'),
                       url(r'^models/(?P<mn>.+)$', 'itemModelAPIViews.itemModelDetail'),
                       url(r'^customerProfiles/$', 'customerProfileViews.customerProfileList'),
                       url(r'^customerProfiles/(?P<uid>[0-9]+)$', 'customerProfileViews.customerProfileDetail'),
                       url(r'^labelNotes/$', 'labelNoteAPIViews.labelNoteList'),
                       url(r'^labelNotes/(?P<pk>[0-9]+)$', 'labelNoteAPIViews.labelNoteDetail'),
                       url(r'^images/$', 'imageAPIViews.imageList'),
                       url(r'^images/(?P<pk>[0-9]+)$', 'imageAPIViews.imageDetail'),
                       url(r'^statuses/$', 'statusViews.statusList'),
                       url(r'^statuses/(?P<pk>[0-9]+)$', 'statusViews.statusDetail'),
                       url(r'^actionstates/$', 'actionStateViews.actionStateList'),
                       url(r'^actionstates/(?P<pk>[0-9]+)$', 'actionStateViews.actionStateDetail'),
                       url(r'^brands/$', 'itemBrandAPIViews.itemBrandList'),
                       url(r'^brands/(?P<pk>[0-9]+)$', 'itemBrandAPIViews.itemBrandDetail'),
                       url(r'^brands/(?P<bn>.+)$', 'itemBrandAPIViews.itemBrandDetail'),
                       url(r'^actionTypes/$', 'actionTypeAPIViews.actionTypeList'),
                       url(r'^actionTypes/(?P<pk>[0-9]+)$', 'actionTypeAPIViews.actionTypeDetail'),
                       url(r'^itemHistory/(?P<fk>[0-9]+)$', 'views.itemHistoryDetail'),
                       url(r'^categoryHierarchy/', 'views.categoryHierarchy'),
                       url(r'^autocomplete/', 'views.autocomplete'),
                       url(r'^itemHistory/(?P<fk>[0-9]+)$', 'views.itemHistoryDetail'),
                       url(r'^reservationHistory/(?P<fk>[0-9]+)$', 'views.reservationHistoryDetail'),)


text:
namespace Incoding.Block.Logging
{
    #region << Using >>

    using System;

    #endregion

    /// <summary>
    ///     Imp <see cref="ILogger" /> for console.
    /// </summary>
    public class ConsoleLogger : LoggerBase
    {
        public override void Log(LogMessage logMessage)
        {
            Console.Write(this.template(logMessage));
        }
    }
}


text:
layout: page
title: Mountain Holdings Trade Fair
date: 2016-05-24
author: Donna Todd
tags: weekly links, java
status: published
summary: In justo elit, malesuada vestibulum sem congue, semper.
banner: images/banner/meeting-01.jpg
booking:
  startDate: 09/05/2016
  endDate: 09/06/2016
  ctyhocn: TXKCRHX
  groupCode: MHTF
published: true
---
In vel iaculis quam. Fusce enim nibh, volutpat ac facilisis nec, consequat eget orci. In hac habitasse platea dictumst. Pellentesque habitant morbi tristique senectus et netus et malesuada fames ac turpis egestas. Maecenas cursus, enim eget semper commodo, erat nulla posuere mi, ac dignissim ante nibh sit amet orci. Mauris vitae mollis quam. Praesent at cursus mauris. Pellentesque ac ipsum eu massa accumsan ultricies. Vivamus posuere velit id felis suscipit faucibus. Aliquam iaculis neque dui, a commodo sem sagittis in. Ut nulla augue, venenatis sit amet eleifend ut, cursus at metus. Curabitur imperdiet vulputate scelerisque. Donec ut felis neque. Quisque eget scelerisque tortor.

* Mauris vitae ex sit amet tellus malesuada sodales
* Aliquam dignissim dolor ac consectetur mattis
* Integer rhoncus odio non suscipit commodo
* Proin pulvinar dui eu purus iaculis, nec consequat odio tempor
* Integer in risus tempor, feugiat augue vel, congue tortor.

Morbi ligula mi, molestie ac commodo interdum, egestas quis leo. Suspendisse purus erat, faucibus at ante sed, euismod pellentesque justo. Aenean nisl sapien, gravida id ipsum sagittis, tempor commodo ex. Pellentesque molestie condimentum justo, id mollis ante ullamcorper et. Donec tempus scelerisque fermentum. Maecenas lectus justo, vestibulum et dictum nec, feugiat et nibh. Fusce aliquet volutpat fermentum. Mauris tristique ultrices dui, sit amet sodales mi. Nunc efficitur diam eget metus pharetra, id ultrices ante euismod. Donec posuere sapien id lacus mattis porttitor. Fusce non lorem maximus, congue lectus vitae, facilisis arcu. Vestibulum vel aliquet urna.


text:
'use strict';

angular.module('app').directive('vehiclesList', function () {

	return {
		restrict: 'E',
		scope: true,
		replace: true,
		templateUrl: 'partials/vehicleslist.html',
		controller: 'VehiclesListController'
	}
});


text:
using System.Collections.Generic;
using System.Linq;
using System.Management.Automation;

namespace PoshCode.Pansies.Commands
{
    [Cmdlet("Write","Host")]
    public class WriteHostCommand : PSCmdlet
    {

        [Parameter(Position=0, ValueFromPipeline=true, ValueFromRemainingArguments=true)]
        public object Object { get; set; }

        [Parameter()]
        public SwitchParameter NoNewline { get; set; }

        [Parameter()]
        public object Separator { get; set; } = " ";
        [Alias("Fg")]
        [Parameter(ValueFromPipelineByPropertyName = true)]
        public RgbColor ForegroundColor { get; set; }

        [Parameter(ValueFromPipelineByPropertyName = true)]
        [Alias("Bg")]
        public RgbColor BackgroundColor { get; set; }

        [Parameter]
        public SwitchParameter PersistentColor { get; set; }

        protected override void ProcessRecord()
        {
            HostInformationMessage informationMessage = new HostInformationMessage();
            informationMessage.Message = Text.GetString(ForegroundColor, BackgroundColor, Object, Separator.ToString(), true, true, PersistentColor);
            informationMessage.NoNewLine = NoNewline.IsPresent;

            var tags = new string[] { "PSHOST" };

            // Discuss: is it worth implementing this, even though Cmdlet.WriteHost won't respect it?
            var value = GetVariableValue("HostPreference", ActionPreference.Continue);
            // NOTE: Anything but Continue and SilentlyContinue (or Ignore) is pointless, since you can set them on Information
            if (value is ActionPreference preference && (preference == ActionPreference.SilentlyContinue || preference == ActionPreference.Ignore))
            {
                tags = new string[] { };
            }

            WriteInformation(informationMessage, tags);
        }
    }
}


text:
#include "base/random.hh"
#include "mem/simple_mem.hh"

using namespace std;

SimpleMemory::SimpleMemory(const SimpleMemoryParams* p) :
    AbstractMemory(p),
    port(name() + ".port", *this), lat(p->latency),
    lat_var(p->latency_var), bandwidth(p->bandwidth),
    isBusy(false), retryReq(false), releaseEvent(this)
{
    printf("[%s:%s:%d] Memory-Side Latency: %lu Bandwidth: %lf\n",
    	__FILE__, __func__, __LINE__,
	p->latency, p->bandwidth);
}

void
SimpleMemory::init()
{
    // allow unconnected memories as this is used in several ruby
    // systems at the moment
    if (port.isConnected()) {
        port.sendRangeChange();
    }
}

Tick
SimpleMemory::calculateLatency(PacketPtr pkt)
{
    if (pkt->memInhibitAsserted()) {
        return 0;
    } else {
        Tick latency = lat;
        if (lat_var != 0)
            latency += random_mt.random<Tick>(0, lat_var);
        return latency;
    }
}

Tick
SimpleMemory::doAtomicAccess(PacketPtr pkt)
{
    access(pkt);
    return calculateLatency(pkt);
}

void
SimpleMemory::doFunctionalAccess(PacketPtr pkt)
{
    functionalAccess(pkt);
}

bool
SimpleMemory::recvTimingReq(PacketPtr pkt)
{
    if (pkt->memInhibitAsserted()) {
        // snooper will supply based on copy of packet
        // still target's responsibility to delete packet
        delete pkt;
        return true;
    }

    // we should never get a new request after committing to retry the
    // current one, the bus violates the rule as it simply sends a
    // retry to the next one waiting on the retry list, so simply
    // ignore it
    if (retryReq)
        return false;

    // if we are busy with a read or write, remember that we have to
    // retry
    if (isBusy) {
        retryReq = true;
        return false;
    }

    // update the release time according to the bandwidth limit, and
    // do so with respect to the time it takes to finish this request
    // rather than long term as it is the short term data rate that is
    // limited for any real memory

    // only look at reads and writes when determining if we are busy,
    // and for how long, as it is not clear what to regulate for the
    // other types of commands
    if (pkt->isRead() || pkt->isWrite()) {
        // calculate an appropriate tick to release to not exceed
        // the bandwidth limit
        Tick duration = pkt->getSize() * bandwidth;

        // only consider ourselves busy if there is any need to wait
        // to avoid extra events being scheduled for (infinitely) fast
        // memories
        if (duration != 0) {
            schedule(releaseEvent, curTick() + duration);
            isBusy = true;
        }
    }

    // go ahead and deal with the packet and put the response in the
    // queue if there is one
    bool needsResponse = pkt->needsResponse();
    Tick latency = doAtomicAccess(pkt);
    // turn packet around to go back to requester if response expected
    if (needsResponse) {
        // doAtomicAccess() should already have turned packet into
        // atomic response
        assert(pkt->isResponse());
        port.schedTimingResp(pkt, curTick() + latency);
    } else {
        delete pkt;
    }

    return true;
}

void
SimpleMemory::release()
{
    assert(isBusy);
    isBusy = false;
    if (retryReq) {
        retryReq = false;
        port.sendRetry();
    }
}

SlavePort &
SimpleMemory::getSlavePort(const std::string &if_name, int idx)
{
    if (if_name != "port") {
        return MemObject::getSlavePort(if_name, idx);
    } else {
        return port;
    }
}

unsigned int
SimpleMemory::drain(Event *de)
{
    int count = port.drain(de);

    if (count)
        changeState(Draining);
    else
        changeState(Drained);
    return count;
}

SimpleMemory::MemoryPort::MemoryPort(const std::string& _name,
                                     SimpleMemory& _memory)
    : QueuedSlavePort(_name, &_memory, queueImpl),
      queueImpl(_memory, *this), memory(_memory)
{ }

AddrRangeList
SimpleMemory::MemoryPort::getAddrRanges() const
{
    AddrRangeList ranges;
    ranges.push_back(memory.getAddrRange());
    return ranges;
}

Tick
SimpleMemory::MemoryPort::recvAtomic(PacketPtr pkt)
{
    return memory.doAtomicAccess(pkt);
}

void
SimpleMemory::MemoryPort::recvFunctional(PacketPtr pkt)
{
    pkt->pushLabel(memory.name());

    if (!queue.checkFunctional(pkt)) {
        // Default implementation of SimpleTimingPort::recvFunctional()
        // calls recvAtomic() and throws away the latency; we can save a
        // little here by just not calculating the latency.
        memory.doFunctionalAccess(pkt);
    }

    pkt->popLabel();
}

bool
SimpleMemory::MemoryPort::recvTimingReq(PacketPtr pkt)
{
    return memory.recvTimingReq(pkt);
}

SimpleMemory*
SimpleMemoryParams::create()
{
    return new SimpleMemory(this);
}


text:
(function() {
  function Authorization($firebaseArray, $firebaseAuth, $state) {
    var ref = firebase.database().ref().child("users");
    var users = $firebaseArray(ref);

    //Get Current User
    var currentUser = $firebaseAuth().$getAuth();
    console.log(currentUser);

    //Creates User
    var createUser = function(email, password, username) {
      $firebaseAuth().$createUserWithEmailAndPassword(email, password)
        .then(function(firebaseUser) {

        firebaseUser.updateProfile({
          displayName: username
        });

        var user = {
          username: username,
          uid: firebaseUser.uid
        };

         users.$add(user);

          console.log("User " + firebaseUser.uid + " created successfully!");
          console.log(firebaseUser);

        }).catch(function(error) {
          console.error("Error: ", error);
        });
    };

    //Sign in User
    var signInUser = function(email, password) {
      $firebaseAuth().$signInWithEmailAndPassword(email, password)
        .then(function(firebaseUser) {
          console.log("Signed in");
        }).catch(function(error) {
          console.error("Authentication failed:", error);
        });
    };

    var signOut = function() {
      $firebaseAuth().$signOut();
      $state.go('welcomePage');
    };

    $firebaseAuth().$onAuthStateChanged(function(firebaseUser) {
      if (firebaseUser) {
        currentUser = firebaseUser;
      } else {
        currentUser = null;
        console.log("Current user is null/signed out");
      }
    });

    var getCurrentUser = function() {
      return currentUser;
    };

    return {
      createUser: createUser,
      signInUser: signInUser,
      getCurrentUser: getCurrentUser,
      authObj: $firebaseAuth(),
      signOut: signOut
    };
  }

  angular
    .module('blocChat')
    .factory('Authorization', ["$firebaseArray","$firebaseAuth","$state", Authorization]);
})();


text:
  Vidaillac est
       un village
       géographiquement positionné dans le département de Lot en Midi-Pyrénées. Elle totalisait 165 habitants en 2008.

Le nombre de logements, à Vidaillac, était réparti en 2011 en un appartements et 115 maisons soit
 un marché plutôt équilibré.

Si vous pensez demenager à Vidaillac, vous pourrez aisément trouver une maison à acheter.

À coté de Vidaillac sont localisées les villes de
Martiel à 8 km, 885 habitants,
Loze située à 6 km, 125 habitants,
Varaire située à 8 km, 296 habitants,
Vailhourles à 7 km, 600 habitants,
Laramière à 4 km, 283 habitants,
Puylagarde localisée à 4 km, 339 habitants,
 entre autres. De plus, Vidaillac est située à seulement 16 km de Villefranche-de-Rouergue.


text:
require 'test/unit'
require 'soap/wsdlDriver'
require 'RAA.rb'
require 'RAAServant.rb'
require 'RAAService.rb'

module WSDL
module RAA

class TestRAA < Test::Unit::TestCase
  DIR = File.dirname(File.expand_path(__FILE__))

  Port = 17171

  def setup
    setup_server
    setup_client
  end

  def setup_server
    @server = App.new('RAA server', nil, '0.0.0.0', Port)
    @server.level = Logger::Severity::ERROR
    @t = Thread.new {
      Thread.current.abort_on_exception = true
      @server.start
    }
  end

  def setup_client
    wsdl = File.join(DIR, 'raa.wsdl')
    @raa = ::SOAP::WSDLDriverFactory.new(wsdl).create_rpc_driver
    @raa.endpoint_url = "http://localhost:#{Port}/"
  end

  def teardown
    teardown_server
    teardown_client
  end

  def teardown_server
    @server.shutdown
    @t.kill
    @t.join
  end

  def teardown_client
    @raa.reset_stream
  end

  def test_raa
    assert_equal(["ruby", "soap4r"], @raa.getAllListings)
  end

  def foo
    p @raa.getProductTree()
    p @raa.getInfoFromCategory(Category.new("Library", "XML"))
    t = Time.at(Time.now.to_i - 24 * 3600)
    p @raa.getModifiedInfoSince(t)
    p @raa.getModifiedInfoSince(DateTime.new(t.year, t.mon, t.mday, t.hour, t.min, t.sec))
    o = @raa.getInfoFromName("SOAP4R")
    p o.type
    p o.owner.name
    p o
  end
end

end
end


text:
function ocr_crop() {
    jQuery(function ($) {
        jQuery.get(baseUrl + '/plugins/ocrstream/include/rest.php', {ref: resourceId, get_true_size: 1}, function (data) {
            trueSize = JSON.parse(data);
            if (trueSize.hasOwnProperty("error")) {
                console.log(trueSize["error"]); //debug
                return;
            }
            w_true = trueSize[0];
            h_true = trueSize[1];
            console.log('original temp image dimensions: ', w_true, h_true); //debug
            var jcrop_api;
            $('.ImageBorder').Jcrop({
                trueSize: [w_true, h_true],
                onChange: setCoords,
                onSelect: setCoords,
                onRelease: clearCoords
            }, function () {
                jcrop_api = this;
            });
            $('#coords').on('change', 'input', function (e) {
                var x1 = $('#x1').val(),
                    y1 = $('#y1').val();
                jcrop_api.setSelect([x1, y1]);
            });
        });
    });
}
function setCoords(c) {
    jQuery('#x1').val(Math.round(c.x));
    jQuery('#y1').val(Math.round(c.y));
    jQuery('#w').val(Math.round(c.w));
    jQuery('#h').val(Math.round(c.h));
    x = (Math.round(c.x));
    y = (Math.round(c.y));
    w = (Math.round(c.w));
    h = (Math.round(c.h));
};
function clearCoords() {
    jQuery('#coords input').val('');
};
function setLanguage(selectedLanguage) {
    ocr_lang = selectedLanguage;
    return ocr_lang;
};
function setPsm(selectedPSM) {
    ocr_psm = selectedPSM;
    return ocr_psm;
};
function setParams(selectedParam) {
    param_1 = selectedParam;
    if (param_1 === 'pre_1') {
        ocr_crop();
    }
    return param_1;
};

function setOCRCron(resourceId) {
    ocr_cron = jQuery('#ocr_cron_start').attr('checked');
    if (ocr_cron === 'checked') {
        ocr_state = '1';
        jQuery.get(baseUrl + '/plugins/ocrstream/include/rest.php', {ref: resourceId, ocr_state: ocr_state}, function (data) {
            var1 = data;
            console.log(var1); // debug
        });
    } else {
        ocr_state = '0';
        jQuery.get(baseUrl + '/plugins/ocrstream/include/rest.php', {ref: resourceId, ocr_state: ocr_state}, function (data) {
            var2 = data;
            console.log(var2); // debug
        });
    }
    console.log(ocr_cron);// debug
    return ocr_cron;
};

function showLoadingImage() {
    jQuery('#ocr_status_anim').show(400);
};
function hideLoadingImage() {
    jQuery('#ocr_status_anim').fadeOut(800);
};

jQuery(document).ready(function () {
    // Get ocr state of resource and set the cronjob checkbox
    jQuery.get(baseUrl + '/plugins/ocrstream/include/rest.php', {ref: resourceId, ocr_state_query: 1}, function (data) {
        ocr_state = JSON.parse(data);
        if (ocr_state === 1) {
            jQuery('#ocr_cron_start').prop('checked', true);
        }
        console.log('ocr_state: ', ocr_state); // debug
        return ocr_state;
    });
    ocr_lang = jQuery('#ocr_lang :selected').text();
    ocr_psm = jQuery('#ocr_psm :selected').val();
    param_1 = jQuery('#im_preset :selected').val();
    x = '0';
    y = '0';
    w = '0';
    h = '0';
    status = 'OCR Stage ';
    // Only show jCrop when image is going to be processed
    if (param_1 === 'pre_1') {
        ocr_crop();
    }
    // Send parameters to stage 1 - 4 for OCR processing
    jQuery('[name="ocr_start"]').on("click", ocrStart);
    function ocrStart (event) {
        jQuery( this ).off( event );
        showLoadingImage();
        console.log(status + '1/4 .'); // debug
        jQuery('#ocr_status_text').html(status + '1/4 .');
        jQuery.get(baseUrl + '/plugins/ocrstream/include/stage_1.php', {ref: resourceId, ocr_lang: ocr_lang, param_1: param_1}, function (data) {
            stageOneOutput = JSON.parse(data);
            console.log(stageOneOutput[1]); // debug
            if (stageOneOutput.hasOwnProperty("error")) {
                hideLoadingImage();
                alert(stageOneOutput["error"]);
                return;
            }
            console.log(status + '2/4 ..'); // debug
            jQuery('#ocr_status_text').html(status + '2/4 ..');
            jQuery.get(baseUrl + '/plugins/ocrstream/include/stage_2.php', {ref: resourceId, ocr_lang: ocr_lang, ocr_psm: ocr_psm, param_1: param_1, w: w, h: h, x: x, y: y}, function (data) {
                stageTwoOutput = JSON.parse(data);
                console.log(stageTwoOutput[1]); // debug
                if (stageTwoOutput.hasOwnProperty("error")) {
                    hideLoadingImage();
                    alert(stageTwoOutput["error"]);
                    return;
                }
                console.log(status + '3/4 ...'); // debug
                jQuery('#ocr_status_text').html(status + '3/4 ...');
                jQuery.get(baseUrl + '/plugins/ocrstream/include/stage_3.php', {ref: resourceId, ocr_lang: ocr_lang, ocr_psm: ocr_psm, param_1: param_1}, function (data) {
                    stageThreeOutput = JSON.parse(data);
                    console.log(stageThreeOutput[1]); // debug
                    if (stageThreeOutput.hasOwnProperty("error")) {
                        hideLoadingImage();
                        alert(stageThreeOutput["error"]);
                        return;
                    }
                    console.log(status + '4/4 ....'); // debug
                    jQuery('#ocr_status_text').html(status + '4/4 ....');
                    jQuery.get(baseUrl + '/plugins/ocrstream/include/stage_4.php', {ref: resourceId}, function (data) {
                        stageFourOutput = JSON.parse(data);
                        console.log(stageFourOutput[1]); // debug
                        if (stageFourOutput.hasOwnProperty("error")) {
                            hideLoadingImage();
                            alert(stageFourOutput["error"]);
                            return;
                        }
                        hideLoadingImage();
                        jQuery('[name="ocr_start"]').on("click", ocrStart);
                        jQuery('#field_' + fieldNr).html(stageFourOutput[2]);
                    });
                });
            });
        });
    };
});


text:
{% load filters %}

<!DOCTYPE html>
<html lang="en">
<head>
  <title>{{ mo_it }}</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
  <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
</head>
<body>

{% include "cQuiz/pieces/header.html" %}
{% block qaform %}
    {% include "cQuiz/pieces/content_body.html" %}
{% endblock %}

</body>
</html>


text:
<?php
defined('BASEPATH') OR exit('No direct script access allowed');

class Produit extends CI_Controller {

	function __construct ()
	{

	parent:: __construct ();
	$this->load->helper(array('form', 'url'));
	$this->load->model('produit/produitsmodel', 'ProduitsModel');

	}

	public function index()
		{
				$this->load->view('produit/produit');
		}

	public function recup(){

		$tout = $this->ProduitsModel->recupAll();
		$data['produits'] = $tout;
		$this->load->view('produit/produit', $data);

	}

	public function sup(){

		$id = $this->uri->segment(3,0);

		$this->ProduitsModel->supprimer($id);

		redirect('produit/recup', 'refresh');

	}

	public function ajouter(){

		$this->load->view('produit/ajouter');

		if($this->input->post('ajouter')){

			$data = array();
			$data['id'] = $this->input->post('id');
			$data['desc'] = $this->input->post('desc');
			$data['date_create'] = $this->input->post('date_create');
			$data['date_update'] = $this->input->post('date_update');

			$this->ProduitsModel->aj($data);

			redirect('produit/recup', 'refresh');

		}
	}

	public function modif(){

		$id = $this->uri->segment(3,0);

		$le = $this->ProduitsModel->recupAll_By_Id($id);
		$data['leproduit'] = $le;
		$this->load->view('produit/modifier', $data);

		if ($this->input->post('modifier')) {

			$data = array();
			$data['desc'] = $this->input->post('desc');
			$data['date_create'] = $this->input->post('date_create');
			$data['date_update'] = $this->input->post('date_update');

			$this->ProduitsModel->up($id, $data);

			redirect('produit/recup', 'refresh');
		}

	}

}


text:
import { AirlineRapidBoard32 } from "../../";

export = AirlineRapidBoard32;


text:
// ***********************************************************************
// Assembly         : Bilal
// Author           : Mahmoud Hasheesh
// Created          : 01-16-2017
//
// Last Modified By : Mahmoud Hasheesh
// Last Modified On : 01-16-2017
// ***********************************************************************
// <copyright file="QiblaViewModel.cs" company="Mahmoud Hasheesh">
//     Licensed under the MIT License. See License.txt in the project root for license information.
// </copyright>
// <summary></summary>
// ***********************************************************************

namespace Bilal
{
    using System;
    using System.Diagnostics;
    using System.Threading;
    using System.Threading.Tasks;

    using GalaSoft.MvvmLight;

    using Plugin.Compass;
    using Plugin.Geolocator;
    using Plugin.Geolocator.Abstractions;

    /// <summary>
    ///     Class MainPageViewModel.
    /// </summary>
    public class QiblaViewModel : ViewModelBase
    {
        private double compassHeading;

        public QiblaViewModel()
        {
            CrossCompass.Current.CompassChanged += (s, e) => { this.CompassHeading = Math.Round(e.Heading, 0); };
            CrossCompass.Current.Start();

            this.locator = CrossGeolocator.Current;
            this.locator.DesiredAccuracy = 50;
            this.locator.PositionChanged += this.LocatorOnPositionChanged;
            this.BearingToKaaba();
        }

        private IGeolocator locator;
        public double Rotation => -1 * this.compassHeading;

        public double CompassHeading
        {
            get
            {
                return this.compassHeading;
            }
            set
            {
                if (Math.Abs(this.compassHeading - value) < double.Epsilon) return;

                this.compassHeading = value;
                this.RaisePropertyChanged();
                this.RaisePropertyChanged("Rotation");
            }
        }

        private double bearing;

        public double Bearing
        {
            get
            {
                return this.bearing;
            }
            set
            {
                if (Math.Abs(this.bearing - value) < double.Epsilon) return;

                this.bearing = value;
                this.RaisePropertyChanged();
            }
        }

        private async Task<Position> GetcurrentLocation()
        {
            try
            {
                //await locator.StartListeningAsync(5000, 10);
                var position = await this.locator.GetPositionAsync();
                return position;
            }
            catch (Exception ex)
            {
                Debug.WriteLine("Unable to get location, may need to increase timeout: " + ex);
                return null;
            }
        }
        private void LocatorOnPositionChanged(object sender, PositionEventArgs positionEventArgs)
        {
            this.BearingToKaaba();
        }

        private async void BearingToKaaba()
        {
            var currentLocation = await this.GetcurrentLocation();
            if (currentLocation != null)
            {
                this.Bearing = GeoHelper.BearingTo(currentLocation.Latitude, currentLocation.Longitude, 21.422487, 39.826206);
            }
        }
    }
}


text:
<!DOCTYPE html>

    <meta charset="utf-8" />
    <meta http-equiv="X-UA-Compatible" content="IE=edge" />

    <title>Principal Component Analysis (PCA) Part - 1</title>
    <meta name="description" content="" />

    <meta name="HandheldFriendly" content="True" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />

    <link rel="shortcut icon" href="//anuragsingh31.github.io/themes/Roon/favicon.ico">

    <link rel="stylesheet" type="text/css" href="//fonts.googleapis.com/css?family=Merriweather:400,700,400italic,700italic|Open+Sans:400italic,700italic,700,400">
    <link rel="stylesheet" type="text/css" href="//anuragsingh31.github.io/themes/Roon/assets/css/screen.css?v=1.0.0" />

    <link rel="canonical" href="https://anuragsingh31.github.io/2015/06/13/Principal-Component-Analysis-PCA-Part-1.html" />

    <meta property="og:site_name" content="Everything about Machine Learning" />
    <meta property="og:type" content="article" />
    <meta property="og:title" content="Principal Component Analysis (PCA) Part - 1" />
    <meta property="og:description" content="Today we will learn about PCA (Principal Component Analysis), PCA is used for dimension Reduction of data, lets find out how it does that! We will talk in detail, from mathematic base to direct one line implementation in Scikit (python..." />
    <meta property="og:url" content="https://anuragsingh31.github.io/2015/06/13/Principal-Component-Analysis-PCA-Part-1.html" />
    <meta property="article:published_time" content="2015-06-12T18:30:00.000Z" />
    <meta property="article:modified_time" content="2015-06-14T08:55:25.950Z" />
    <meta property="article:tag" content="Algorithms" />

    <meta name="twitter:card" content="summary" />
    <meta name="twitter:title" content="Principal Component Analysis (PCA) Part - 1" />
    <meta name="twitter:description" content="Today we will learn about PCA (Principal Component Analysis), PCA is used for dimension Reduction of data, lets find out how it does that! We will talk in detail, from mathematic base to direct one line implementation in Scikit (python..." />
    <meta name="twitter:url" content="https://anuragsingh31.github.io/2015/06/13/Principal-Component-Analysis-PCA-Part-1.html" />

    <meta name="generator" content="Ghost ?" />
    <link rel="alternate" type="application/rss+xml" title="Everything about Machine Learning" href="https://anuragsingh31.github.io/rss" />
    <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/highlight.js/8.4/styles/default.min.css">

            «

<time datetime="2015-06-13">June 13, 2015</time>

Principal Component Analysis (PCA) Part - 1

Today we will learn about PCA (Principal Component Analysis), PCA is used for dimension
Reduction of data, lets find out how it does that!

We will talk in detail, from mathematic base to direct one line implementation in Scikit (python library for machine learning). Those who are only interested in one liner implementation can skip to the Part - 2.

But we will strongly advice against that, one must know what's going on under the hood in order to be able to utilize it effectively, this small difference is the key here. So  if you have revised basics of Statistics and Linear algebra as said in our last post let's continue.

What the hell is Principal Component Analysis ?

When we have lots of data, we try to remove the reduntant part and utilise only important information.

Assume you are on diet, and obviously you are hungry and when you open the refrigerator, your roommate has placed a large creamy chocolate cake just to mess with you, you are salivating now. So you try to come up with the reasons should i eat it or not ? When deciding it what information will help you ?

so you look on the box of cake, there is:

Company name

Address of the bakery

Calories count

Name of the delivery boy

Manufacturing date

Content of the cake

Contact number

Total 7  (Called features in machine learning lingo).

so what of the above information will help you ?
The smart ass like you will directly check calories count and content of the cake and Manufacturing date some of us may check company name also for trust issues.

See rest is irrelevant information all redundant data, you removed it in an instant. So only 3 features were helpful for us out of 7.

Similarly in the world of machine learning when we have Gigabytes or Terabytes of data and we want to play with it and can’t manually identify relavent information, PCA helps us.

Basically PCA detects correlation between variables, if strong correlation exists we attempt to reduce the dimensionality. It does that by finding the direction of maximum variance(Relavent information for us) in high Dimensional data and project it on to a smaller dimensional subspace ( an example below will help in better understanding it).

Let's Start

In PCA we calculate Eigen vector and Eigen value, they come in pairs.
You might know how to compute Eigen vectors and Eigen values but what are they?

How are they helping us?

Eigen Vector tells us the direction of Principal Component and It's corresponding Eigen
value will tell us how much variance (Relavent information for us) is there in data in that direction,

Greater the value of Eigen value, greater is the variance in that direction.
The amount of Eigen vectors/ values that exists equals the no. of dimensions that data has. Like in our cake example we had 7 so we will have 7 Eigenvector/value pairs.

Out of which we will remove the Eigen vectors with least Eigen values like we removed the features (contact number, delivery boy signature , address etc.)

Now let's take a look at an example for better understanding.
Suppose we have 3- Dimensional data of 100,000 Flats. We have 3 features House size,
No. of rooms and Floor no. of the Flat. And if we plot it , it will look something like this

Suppose if we calculate  Principal Component( Eigen vectors) and plot them in above figure, it will look like this

Suppose EV1, EV2 and EV3 are Eigen vectors with Eigen value of 10, 3 and 0 for House size, no. of rooms and Floor number respectively.
We see that EV1 has the highest Eigen value and EV2 has non negative Eigen value, but EV3 has 0 value
(i.e no Height/no valuable data) which means Floor number is not a significant feature while deciding which flat to buy.

So we can remove this dimension and plot again in new subspace if EV1 and EV2 rather than X, Y and Z,
by doing so we get data with reduced dimensions while retaining important information.

So this is what it will look like in sub dimension space, and now we can work on it further.

Steps involved in PCA

Standardize the data

Calculate Eigen vector and Eigen values from covariance matrix after       standardizing,or directly from correlation matrix which is same as
covariance matrix but is already standardized.  Another way is
Singular Vector Decomposition

If N is the no. of dimensions in new subspace, sort top N Eigen
values in descending order and choose their eigen vectors accordingly.

Construct projection matrix B from selected Eigen vectors

Transform original dataset A via B to get reduced N-dimensional
feature subspace Z.

As in Part 1 we learned the what is happening in here in Part 2 we will see how to do it mathematically and practically with python.

        <menu>

                Share

                 Comment on Twitter

        </menu>

      Please enable JavaScript to view the comments powered by Disqus.
      comments powered by Disqus

                    Share
                    ×

                    Tweet


text:
require File.expand_path('../../../../test/test_helper', __FILE__)

describe Dracula::Sentence do

  subject { Dracula::Sentence }

  it "must return a random sentence" do
    subject.sentence.must_be_instance_of(String)
  end

  it "must return 5 sentences by default" do
    subject.sentences.size.must_equal(5)
  end

  it "must return the specified amount of sentences" do
    subject.sentences(10).size.must_equal(10)
  end

end


text:
(function($) {

	module('ncanvas', {
		setup: function() {
			this.canvas = $nc(document.getElementById("sample"), {});
		}
	});

	test("canvas creation", function() {
		ok(this.canvas !== undefined, "Passed!");
	});

	test("canvas layer", function() {
		var layer = this.canvas.layer(0, 0, 200, 200);
		ok(layer !== undefined, "Passed!");
	});

})();


text:
package com.teddy.lc4e.core.web.controller.view;

import com.teddy.lc4e.core.entity.webui.Article;
import com.teddy.lc4e.core.entity.webui.Data;
import com.teddy.lc4e.core.entity.webui.Message;
import com.teddy.lc4e.core.entity.webui.Popup;
import com.teddy.lc4e.core.web.service.ComVariableData;
import com.teddy.lc4e.core.web.service.InitDBService;
import com.teddy.lc4e.core.web.service.WebCacheManager;
import com.teddy.lc4e.plugins.annotation.*;
import com.teddy.lc4e.plugins.tools.ParserMessage;
import com.teddy.lc4e.plugins.tools.RelativeDate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.LocaleResolver;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.text.SimpleDateFormat;
import java.util.*;

@Controller
public class ViewController {

    @Autowired
    private ParserMessage msg;

    @Autowired
    private InitDBService initDataBaseService;

    @Autowired
    private WebCacheManager webCacheManager;

    @Autowired
    private LocaleResolver localeResolver;

    @Autowired
    private ComVariableData comVariableData;

    @Autowired
    private RelativeDate dateFormat;

    @ValidateParams(fields = {@ValidateParam(index = 3, defaultValue = "1")})
    @RequestMapping(value = {"/Page/{page}"}, method = RequestMethod.GET)
    @ResponseBody
    public Message home(HttpServletRequest request, HttpServletResponse response, Model model, @PathVariable("page") Integer page, Locale locale) {
        Integer size = (Integer) comVariableData.getComVarByName("IndexPageSize");
        String[] cate = new String[]{"Java", "Obj-C", "C", "C++", "IOS", "Android"};
        String[] users = new String[]{"Admin", "Test", "Myas", "Liakx", "Google", "vsss"};
        Date now = new Date();
        List<Article> list = new ArrayList<Article>();
        for (int i = 0; i < size; i++) {
            list.add(new Article("/images/wireframe/image.png", new Popup("Matt", "Matt has been a member since July 2014"), "The friction between your thoughts and your code", cate[new Random().nextInt(cate.length - 1)], users[new Random().nextInt(users.length - 1)], new Random().nextInt(100),
                    dateFormat.format(randomDate("2015-05-11 13:00:00", now), locale, now), users[new Random().nextInt(users.length - 1)]));
        }
        return new Message(true, new Data("list", list));
    }

    @RequestMapping(value = {"/"}, method = RequestMethod.GET)
    @SetUIDatas(fields = {@SetUIData(functionName = "getMenuTree", attributeName = "menulist", key = "menus")})
    @SetComVar(comVar = {"SiteName"})
    @ValidateParams(fields = {@ValidateParam(index = 3, defaultValue = "1")})
    public String homeIndex(HttpServletRequest request, HttpServletResponse response, Model model, Integer p) {
        model.addAttribute("page", p);
        return "index";
    }

    @RequestMapping(value = "/articleTemplate", method = RequestMethod.GET)
    public String articleTemplate(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "template/articleIndex";
    }

    @RequestMapping(value = "/Articles", method = RequestMethod.GET)
    public String articletest(HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) {
        Integer size = (Integer) comVariableData.getComVarByName("IndexPageSize");
        String[] cate = new String[]{"Java", "Obj-C", "C", "C++", "IOS", "Android"};
        String[] users = new String[]{"Admin", "Test", "Myas", "Liakx", "Google", "vsss"};
        Date now = new Date();
        List<Article> list = new ArrayList<Article>();
        for (int i = 0; i < size; i++) {
            list.add(new Article("/images/wireframe/image.png", new Popup("Matt", "Matt has been a member since July 2014"), "The friction between your thoughts and your code", cate[new Random().nextInt(cate.length - 1)], users[new Random().nextInt(users.length - 1)], new Random().nextInt(100),
                    dateFormat.format(randomDate("2015-05-11 13:00:00", now), locale, now), users[new Random().nextInt(users.length - 1)]));
        }
        model.addAttribute("lists", list);
        return "template/article";
    }

    @RequestMapping(value = "/Exception", method = RequestMethod.GET)
    public String exception(HttpServletRequest request, HttpServletResponse response, Model model) {
        Map params = request.getParameterMap();
        for (Object key : params.keySet()) {
            model.addAttribute(key.toString(), ((String[]) params.get(key))[0]);
        }
        return "/exceptions/common";
    }

    @RequestMapping(value = "/TopHots", method = RequestMethod.GET)
    public String tophostsTest(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "topHotTest";
    }

    @ValidateToken
    @RequestMapping(value = "/TestShiro", method = RequestMethod.GET)
    public String test(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "topHotTest";
    }

    @RequestMapping(value = "/View", method = RequestMethod.GET)
    public String View(HttpServletRequest request, HttpServletResponse response, Model model, Locale locale) {
        model.addAttribute("exception", msg.L18N("test", locale));
        return "unauthorized";
    }

    @RequestMapping(value = "/ChangeLocale", method = RequestMethod.GET)
    @ResponseBody
    public Message ChangeLocale(HttpServletRequest request, HttpServletResponse response, Model model) {
        localeResolver.setLocale(request, response, Locale.CHINA);
        return new Message(true, "Change Success");
    }

    @RequestMapping(value = "/GetMenus", method = RequestMethod.GET)
    @SetUIDatas(fields = {@SetUIData(functionName = "getMenuTree", attributeName = "Message", key = " ")})
    public String getMenus(HttpServletRequest request, HttpServletResponse response, Model model) {
        return "System/Message";
    }

    @RequestMapping(value = "/ClearCache", method = RequestMethod.GET)
    @ValidateParams(fields = {@ValidateParam(index = 3, required = true), @ValidateParam(index = 4, required = true)})
    @ResponseBody
    public Message getMenus2(HttpServletRequest request, HttpServletResponse response, Model model, String cacheName, String key) {
        if (webCacheManager.clearCacheByCacheNameAndKey(cacheName, key))
            return new Message(true, "clear success");
        else
            return new Message(false, "clear failed");
    }

    @RequestMapping(value = "/InitDB", method = RequestMethod.GET)
    @ResponseBody
    public Message initaldb(HttpServletRequest request, HttpServletResponse response, Model model) {
        if (initDataBaseService.initdb()) {
            return new Message(true, "success");
        }
        return new Message("failed");
    }

    private static Date randomDate(String beginDate, Date endDate) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start = format.parse(beginDate);
            Date end = endDate;
            if (start.getTime() >= end.getTime()) {
                return null;
            }
            long date = random(start.getTime(), end.getTime());

            return new Date(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static Date randomDate(String beginDate, String endDate) {
        try {
            SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date start = format.parse(beginDate);
            Date end = format.parse(endDate);
            if (start.getTime() >= end.getTime()) {
                return null;
            }
            long date = random(start.getTime(), end.getTime());

            return new Date(date);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return null;
    }

    private static long random(long begin, long end) {
        long rtnn = begin + (long) (Math.random() * (end - begin));
        if (rtnn == begin || rtnn == end) {
            return random(begin, end);
        }
        return rtnn;
    }

}


text:
joCache.set("widgets", function() {
	var slider;
	var card = new joCard([
		new joTitle("Input Boxes"),
		new joGroup([
			new joLabel("joInput"),
			new joFlexrow(new joInput("Hello, Jo!")),
			new joLabel("joPasswordInput"),
			new joFlexrow(new joPasswordInput("password")),
			new joLabel("joInput with Placeholder"),
			new joFlexrow(new joInput("", "Placeholder Text")),
			new joLabel("joTextArea"),
			new joFlexrow(new joTextarea("This is some multi-line text, Jo!")),
			new joDivider(),
			new joFlexrow([
				new joLabel("Left Aligned").setStyle({className: "left", marginTop: "2px"}),
				new joInput("From CSS").setStyle({width: "150px", marginBottom: "0"})
			])
		]),
		new joTitle("Selection Widgets"),
		new joGroup([
			new joLabel("joOption"),
			new joFlexrow(new joOption([
				"Red", "Green", "Blue"
			])),
			new joLabel("joSelect"),
			new joSelect([
				"Baked Alaska",
				"Chocolate Mousse",
				"Rum Raisin Ice Cream",
				"Fudge Sundae"
			]).openEvent.subscribe(function(data, select) {
				console.log(select);
				App.stack.scrollTo(select);
			}),
			new joFlexrow([
				new joLabel("joToggle").setStyle("left"),
				new joToggle(true)
			]),
			new joFlexrow([
				new joLabel("With customized labels").setStyle("left"),
				new joToggle().setLabels(["No", "Yes"])
			])
		]),
		new joExpando([
			new joExpandoTitle("joExpando"),
			new joExpandoContent([
				new joLabel("Tuck away more UI controls"),
				new joFlexrow(new joInput("Hello again, Jo!"))
			])
		]),
		new joDivider(),
		new joButton("joButton").selectEvent.subscribe(function() {
			App.scn.alert("You pressed a button!");
		}),
		new joButton("Disabled").disable(),
		new joGroup([
			new joLabel("joSlider"),
			slider = new joSlider(),
			new joLabel("joSlider range 0 - 9, snap 1"),
			slider = new joSlider(4).setRange(0, 9, 1).changeEvent.subscribe(function(value) {
				console.log("value: " + value);
			}, this)
		])
	]).setTitle("Form Widgets");

	return card;
});