text:
/*------------------------------------------------------------------------*/
/*                 Copyright 2010 Sandia Corporation.                     */
/*  Under terms of Contract DE-AC04-94AL85000, there is a non-exclusive   */
/*  license for use of this work by or on behalf of the U.S. Government.  */
/*  Export of this program may require a license from the                 */
/*  United States Government.                                             */
/*------------------------------------------------------------------------*/

#include <stk_mesh/baseImpl/FieldBaseImpl.hpp>

#include <cstring>
#include <stdexcept>
#include <iostream>
#include <sstream>
#include <algorithm>

#include <stk_util/util/SimpleArrayOps.hpp>

#include <stk_mesh/base/Types.hpp>
#include <stk_mesh/base/FieldBase.hpp>
#include <stk_mesh/base/Part.hpp>
#include <stk_mesh/base/MetaData.hpp>
#include <stk_mesh/base/Trace.hpp>

namespace stk {
namespace mesh {
namespace impl {

//----------------------------------------------------------------------

namespace {

struct FieldRestrictionLess {
  bool operator()( const FieldRestriction & lhs ,
                   const FieldRestriction & rhs ) const
    { return lhs.key < rhs.key ; }

  bool operator()( const FieldRestriction & lhs ,
                   const EntityKey & rhs ) const
    { return lhs.key < rhs ; }
};

FieldRestrictionVector::const_iterator
  find( const FieldRestrictionVector & v , const EntityKey & key )
{
  FieldRestrictionVector::const_iterator
    i = std::lower_bound( v.begin() , v.end() , key , FieldRestrictionLess() );

  if ( i != v.end() && i->key != key ) { i = v.end(); }

  return i ;
}

}

//----------------------------------------------------------------------

FieldBaseImpl::FieldBaseImpl(
    MetaData                   * arg_mesh_meta_data ,
    unsigned                     arg_ordinal ,
    const std::string          & arg_name ,
    const DataTraits           & arg_traits ,
    unsigned                     arg_rank,
    const shards::ArrayDimTag  * const * arg_dim_tags,
    unsigned                     arg_number_of_states ,
    FieldState                   arg_this_state
    )
: m_name( arg_name ),
  m_attribute(),
  m_data_traits( arg_traits ),
  m_meta_data( arg_mesh_meta_data ),
  m_ordinal( arg_ordinal ),
  m_num_states( arg_number_of_states ),
  m_this_state( arg_this_state ),
  m_rank( arg_rank ),
  m_dim_map()
{
  TraceIfWatching("stk::mesh::impl::FieldBaseImpl::FieldBaseImpl", LOG_FIELD, m_ordinal);

  FieldBase * const pzero = NULL ;
  const shards::ArrayDimTag * const dzero = NULL ;
  Copy<MaximumFieldStates>(    m_field_states , pzero );
  Copy<MaximumFieldDimension>( m_dim_tags ,     dzero );

  for ( unsigned i = 0 ; i < arg_rank ; ++i ) {
    m_dim_tags[i] = arg_dim_tags[i];
  }
}

const FieldRestrictionVector & FieldBaseImpl::restrictions() const
{ return m_field_states[0]->m_impl.m_dim_map ; }

FieldRestrictionVector & FieldBaseImpl::restrictions()
{ return m_field_states[0]->m_impl.m_dim_map ; }

//----------------------------------------------------------------------

namespace {

void print_restriction( std::ostream & os ,
                        unsigned type ,
                        const Part & part ,
                        unsigned rank ,
                        const FieldRestriction::size_type * stride )
{
  os << "{ entity_rank(" << type << ") part(" << part.name() << ") : " ;
  os << stride[0] ;
  for ( unsigned i = 1 ; i < rank ; ++i ) {
    if ( ! stride[i] ) {
      os << " , 0 " ;
    }
    else if ( stride[i] % stride[i-1] ) {
      os << " , " << stride[i] << " / " << stride[i-1] ;
    }
    else {
      os << " , " << stride[i] / stride[i-1] ;
    }
  }
  os << " }" ;
}

std::string print_restriction( unsigned type ,
                               const Part & part ,
                               unsigned rank ,
                               const FieldRestriction::size_type * stride )
{
  std::ostringstream oss;
  print_restriction(oss, type, part, rank, stride);
  return oss.str();
}

}

// Setting the dimension for one field sets the dimension
// for the corresponding fields of the FieldState array.
// If subset exists then replace it.
// If exists or superset exists then do nothing.

void FieldBaseImpl::insert_restriction(
  const char     * arg_method ,
  EntityRank       arg_entity_rank ,
  const Part     & arg_part ,
  const unsigned * arg_stride )
{
  TraceIfWatching("stk::mesh::impl::FieldBaseImpl::insert_restriction", LOG_FIELD, m_ordinal);

  FieldRestriction tmp ;

  tmp.key = EntityKey( arg_entity_rank , arg_part.mesh_meta_data_ordinal() );

  {
    unsigned i = 0 ;
    if ( m_rank ) {
      for ( i = 0 ; i < m_rank ; ++i ) { tmp.stride[i] = arg_stride[i] ; }
    }
    else { // Scalar field is 0 == m_rank
      i = 1 ;
      tmp.stride[0] = 1 ;
    }
    // Remaining dimensions are 1, no change to stride
    for ( ; i < MaximumFieldDimension ; ++i ) {
      tmp.stride[i] = tmp.stride[i-1] ;
    }

    for ( i = 1 ; i < m_rank ; ++i ) {
      const bool bad_stride = 0 == tmp.stride[i] ||
                              0 != tmp.stride[i] % tmp.stride[i-1];
      ThrowErrorMsgIf( bad_stride,
          arg_method << " FAILED for " << *this <<
          " WITH BAD STRIDE " <<
          print_restriction( arg_entity_rank, arg_part, m_rank, tmp.stride));;
    }
  }

  {
    FieldRestrictionVector & rMap = restrictions();

    FieldRestrictionVector::iterator i = rMap.begin(), j = rMap.end();

    i = std::lower_bound(i,j,tmp,FieldRestrictionLess());

    if ( i == j || i->key != tmp.key ) {
      rMap.insert( i , tmp );
    }
    else {
      ThrowErrorMsgIf( Compare<MaximumFieldDimension>::not_equal(i->stride,tmp.stride),
          arg_method << " FAILED for " << *this << " " <<
          print_restriction( arg_entity_rank, arg_part, m_rank, i->stride ) <<
          " WITH INCOMPATIBLE REDECLARATION " <<
          print_restriction( arg_entity_rank, arg_part, m_rank, tmp.stride ));
    }
  }
}

void FieldBaseImpl::verify_and_clean_restrictions(
  const char       * arg_method ,
  const PartVector & arg_all_parts )
{
  TraceIfWatching("stk::mesh::impl::FieldBaseImpl::verify_and_clean_restrictions", LOG_FIELD, m_ordinal);

  const EntityKey invalid_key ;
  FieldRestrictionVector & rMap = restrictions();
  FieldRestrictionVector::iterator i , j ;

  for ( i = rMap.begin() ; i != rMap.end() ; ++i ) {
    if ( i->key != invalid_key ) {
      const unsigned typeI = entity_rank( i->key );
      const Part   & partI = * arg_all_parts[ entity_id( i->key ) ];
      bool  found_superset = false ;

      for ( j = i + 1 ; j != rMap.end() && ! found_superset ; ++j ) {
        if ( j->key != invalid_key ) {
          const unsigned typeJ = entity_rank( j->key );
          const Part   & partJ = * arg_all_parts[ entity_id( j->key ) ];

          if ( typeI == typeJ ) {
            const bool found_subset = contain( partI.subsets() , partJ );
            found_superset = ! found_subset &&
                             contain( partI.supersets() , partJ );

            if ( found_subset || found_superset ) {
              ThrowErrorMsgIf( Compare< MaximumFieldDimension >::not_equal( i->stride , j->stride ),
                  arg_method << "[" << *this << "] FAILED: " <<
                  print_restriction( typeI, partI, m_rank, i->stride ) <<
                  ( found_subset ? " INCOMPATIBLE SUBSET " : " INCOMPATIBLE SUPERSET ") <<
                  print_restriction( typeJ, partJ, m_rank, j->stride ));
            }

            if ( found_subset ) { j->key = invalid_key; }
          }
        }
        if ( found_superset ) { i->key = invalid_key; }
      }
    }
  }

  // Clean out redundant entries:
  // NOTE: test for 'i != rMap.end()' not needed since i is
  //       incremented no more than j and j is checked. Keeping check in
  //       silences klocwork and guards against future change...
  for ( j = i = rMap.begin() ; j != rMap.end() && i != rMap.end(); ++j ) {
    if ( j->key != invalid_key ) {
      if ( i->key == invalid_key ) {
        *i = *j ;
      }
      ++i ;
    }
  }

  rMap.erase( i , j );
}

//----------------------------------------------------------------------
//----------------------------------------------------------------------
// This part or any superset of this part

const FieldRestriction &
FieldBaseImpl::restriction( unsigned entity_rank , const Part & part ) const
{
  static const FieldRestriction empty ;

  const FieldRestrictionVector & rMap = restrictions();
  const FieldRestrictionVector::const_iterator ie = rMap.end() ;
        FieldRestrictionVector::const_iterator i ;

  const PartVector::const_iterator ipe = part.supersets().end();
        PartVector::const_iterator ip  = part.supersets().begin() ;

  // Start with this part:
  EntityKey key = EntityKey( entity_rank , part.mesh_meta_data_ordinal() );

  while ( ie == ( i = find( rMap , key ) ) && ipe != ip ) {
    // Not found try another superset part:
    key = EntityKey( entity_rank , (*ip)->mesh_meta_data_ordinal() );
    ++ip ;
  }

  return ie == i ? empty : *i ;
}

unsigned FieldBaseImpl::max_size( unsigned entity_rank ) const
{
  unsigned max = 0 ;

  const FieldRestrictionVector & rMap = restrictions();
  const FieldRestrictionVector::const_iterator ie = rMap.end() ;
        FieldRestrictionVector::const_iterator i = rMap.begin();

  for ( ; i != ie ; ++i ) {
    if ( i->type() == entity_rank ) {
      const unsigned len = m_rank ? i->stride[ m_rank - 1 ] : 1 ;
      if ( max < len ) { max = len ; }
    }
  }

  return max ;
}

void FieldBaseImpl::set_field_states( FieldBase ** field_states)
{
  TraceIfWatching("stk::mesh::impl::FieldBaseImpl::set_field_states", LOG_FIELD, m_ordinal);

  for (unsigned i = 0; i < m_num_states; ++i) {
    m_field_states[i] = field_states[i];
  }
}

//----------------------------------------------------------------------

//----------------------------------------------------------------------

std::ostream & operator << ( std::ostream & s , const FieldBaseImpl & field )
{
  s << "FieldBaseImpl<" ;
  s << field.data_traits().name ;
  for ( unsigned i = 0 ; i < field.rank() ; ++i ) {
    s << "," << field.dimension_tags()[i]->name();
  }
  s << ">" ;

  s << "[ name = \"" ;
  s << field.name() ;
  s << "\" , #states = " ;
  s << field.number_of_states();
  s << " ]" ;
  return s ;
}

std::ostream & print( std::ostream & s ,
                      const char * const b ,
                      const FieldBase & field )
{
  const PartVector & all_parts = MetaData::get(field).get_parts();
  const std::vector<FieldBase::Restriction> & rMap = field.restrictions();
  s << field.name() ;
  s << " {" ;
  for ( FieldBase::RestrictionVector::const_iterator
        i = rMap.begin() ; i != rMap.end() ; ++i ) {
    s << std::endl << b << "  " ;
    print_restriction( s, entity_rank( i->key ),
                       * all_parts[ entity_id( i->key ) ],
	               field.rank(), i->stride);
    s << std::endl;
  }
  s << std::endl << b << "}" ;
  return s ;
}

//----------------------------------------------------------------------

} // namespace impl
} // namespace mesh
} // namespace stk


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Linq;
using NExpect;
using NUnit.Framework;
using PeanutButter.RandomGenerators;
using PeanutButter.TestUtils.Generic;
using PeanutButter.Utils.Dictionaries;
using static NExpect.Expectations;
using static PeanutButter.RandomGenerators.RandomValueGen;

// ReSharper disable InconsistentNaming
// ReSharper disable CollectionNeverUpdated.Local

namespace PeanutButter.Utils.Tests.Dictionaries
{
    [TestFixture]
    public class TestDefaultDictionary
    {
        [Test]
        public void Type_ShouldImplement_IDictionary()
        {
            // Arrange
            var sut = typeof(DefaultDictionary<string, bool>);

            // Pre-assert

            // Act
            sut.ShouldImplement<IDictionary<string, bool>>();

            // Assert
        }

        [Test]
        public void IndexedValue_GivenNoDefaultResolverAtConstruction_WhenAskedForMissingValue_ShouldReturnDefaultOfT()
        {
            // Arrange
            var sut = Create<string, bool>();
            var key = RandomValueGen.GetRandomString();

            // Pre-assert

            // Act
            var result = sut[key];

            // Assert
            Expect(result).To.Equal(default(bool));
        }

        [Test]
        public void IndexedValue_GivenDefaultResolverAtConstruction_ShouldReturnThatValue()
        {
            // Arrange
            var expected = RandomValueGen.GetRandomString();
            var key = RandomValueGen.GetRandomString();
            var sut = Create<string, string>(() => expected);

            // Pre-assert

            // Act
            var result = sut[key];

            // Assert
            Expect(result).To.Equal(expected);
        }

        [Test]
        public void IEnumerableEnumerator()
        {
            // Arrange
            var sut = Create<string, string>(() => "moo");
            // Pre-assert
            // Act
            sut["cow"] = "beef";
            var result = new List<KeyValuePair<string, string>>();
            foreach (KeyValuePair<string, string> kvp in (sut as IEnumerable))
            {
                result.Add(kvp);
            }

            // Assert
            Expect(result).To.Contain.Only(1)
                .Deep.Equal.To(new KeyValuePair<string, string>("cow", "beef"));
        }

        [Test]
        public void IndexedValue_WhenKeyExists_ShouldReturnThatValue()
        {
            // Arrange
            var expected = RandomValueGen.GetRandomString();
            var key = RandomValueGen.GetRandomString();
            var unexpected = RandomValueGen.GetAnother(expected);
            var sut = Create<string, string>(() => unexpected);

            // Pre-assert

            // Act
            sut[key] = expected;
            var result = sut[key];

            // Assert
            Expect(result).To.Equal(expected);
        }

        [Test]
        public void ContainsKey_ShouldReturnTrue()
        {
            // Arrange
            var haveKey = RandomValueGen.GetRandomString();
            var missingKey = RandomValueGen.GetAnother(haveKey);
            var sut = Create<string, string>();
            sut[haveKey] = RandomValueGen.GetRandomString();

            // Pre-assert

            // Act
            var haveResult = sut.ContainsKey(haveKey);
            var missingResult = sut.ContainsKey(missingKey);

            // Assert
            Expect(haveResult).To.Be.True();
            Expect(missingResult).To.Be.True();
        }

        [Test]
        public void Enumeration_ShouldPassThrough()
        {
            // Arrange
            var k1 = RandomValueGen.GetRandomString();
            var k2 = RandomValueGen.GetAnother(k1);
            var v1 = RandomValueGen.GetRandomString();
            var v2 = RandomValueGen.GetAnother(v1);
            var sut = Create<string, string>();
            sut[k1] = v1;
            sut[k2] = v2;
            var collector = new List<KeyValuePair<string, string>>();

            // Pre-assert

            // Act
            foreach (var kvp in sut)
            {
                collector.Add(kvp);
            }

            // Assert
            Expect(collector.Count).To.Equal(2);
            Expect(collector).To.Contain.Exactly(1).Equal.To(new KeyValuePair<string, string>(k1, v1));
            Expect(collector).To.Contain.Exactly(1).Equal.To(new KeyValuePair<string, string>(k2, v2));
        }

        [Test]
        public void Add_GivenKeyValuePair_ShouldPassThrough()
        {
            // Arrange
            var sut = Create<string, string>();
            var kvp = RandomValueGen.GetRandom<KeyValuePair<string, string>>();

            // Pre-assert

            // Act
            sut.Add(kvp);

            // Assert
            Expect(sut[kvp.Key]).To.Equal(kvp.Value);
        }

        [Test]
        public void Clear_ShouldPassThrough()
        {
            // Arrange
            var sut = Create<string, string>();
            var item = RandomValueGen.GetRandom<KeyValuePair<string, string>>();
            sut.Add(item);

            // Pre-assert
            Expect(sut[item.Key]).To.Equal(item.Value);

            // Act
            sut.Clear();

            // Assert
            Expect(sut[item.Key]).To.Be.Null();
        }

        [Test]
        public void Contains_ShouldReturnTrue()
        {
            // Arrange
            var have = RandomValueGen.GetRandom<KeyValuePair<string, string>>();
            var missing = RandomValueGen.GetAnother(have);
            var sut = Create<string, string>();
            sut.Add(have);

            // Pre-assert

            // Act
            var haveResult = sut.Contains(have);
            var missingResult = sut.Contains(missing);

            // Assert
            Expect(haveResult).To.Be.True();
            Expect(missingResult).To.Be.True();
        }

        [Test]
        public void Remove_GivenKeyValuePair_ShouldPassThrough_SortOf()
        {
            // Arrange
            var have = RandomValueGen.GetRandom<KeyValuePair<string, string>>();
            var missing = RandomValueGen.GetAnother(have);
            var sut = Create<string, string>();
            sut.Add(have);

            // Pre-assert
            Expect(sut[have.Key]).Not.To.Be.Null();

            // Act
            var haveResult = sut.Remove(have);
            var missingResult = sut.Remove(missing);

            // Assert
            Expect(haveResult).To.Be.True();
            Expect(missingResult).To.Be.False();
            Expect(sut[have.Key]).To.Be.Null();
        }

        [Test]
        public void Remove_GivenKey_ShouldPassThrough()
        {
            // Arrange
            var have = RandomValueGen.GetRandom<KeyValuePair<string, string>>();
            var missing = RandomValueGen.GetAnother(have);
            var sut = Create<string, string>();
            sut.Add(have);
            Expect(sut[have.Key]).Not.To.Be.Null();

            // Pre-assert

            // Act
            var haveResult = sut.Remove(have.Key);
            var missingResult = sut.Remove(missing.Key);

            // Assert
            Expect(haveResult).To.Be.True();
            Expect(missingResult).To.Be.False();
            Expect(sut[have.Key]).To.Be.Null();
        }

        [Test]
        public void Add_GivenKeyAndValue_ShouldPassThrough()
        {
            // Arrange
            var sut = Create<string, string>();
            var kvp = RandomValueGen.GetRandom<KeyValuePair<string, string>>();

            // Pre-assert

            // Act
            sut.Add(kvp.Key, kvp.Value);

            // Assert
            Expect(sut[kvp.Key]).To.Equal(kvp.Value);
        }

        [Test]
        public void TryGetValue_WhenKeyIsKnown_ShouldReturnThatValue()
        {
            // Arrange
            var have = RandomValueGen.GetRandom<KeyValuePair<string, string>>();
            var sut = Create<string, string>();
            sut.Add(have);

            // Pre-assert

            // Act
            var result = sut.TryGetValue(have.Key, out var found);

            // Assert
            Expect(result).To.Be.True();
            Expect(found).To.Equal(have.Value);
        }

        [Test]
        public void TryGetValue_WhenKeyIsUnknown_ShouldReturnDefault()
        {
            // Arrange
            var expected = RandomValueGen.GetRandomString();
            var sut = Create<string, string>(() => expected);

            // Pre-assert

            // Act
            var result = sut.TryGetValue(RandomValueGen.GetRandomString(), out var found);

            // Assert
            Expect(result).To.Be.True();
            Expect(found).To.Equal(expected);
        }

        [Test]
        public void CopyTo_ShouldCopyKnownKeyValuePairs()
        {
            // Arrange
            var start = RandomValueGen.GetRandomInt(2, 4);
            var arraySize = RandomValueGen.GetRandomInt(10, 15);
            var items = RandomValueGen.GetRandomArray<KeyValuePair<string, string>>(2, 4);
            var target = new KeyValuePair<string, string>[arraySize];
            var sut = Create<string, string>();
            items.ForEach(sut.Add);

            // Pre-assert

            // Act
            sut.CopyTo(target, start);

            // Assert
            var defaultValue = default(KeyValuePair<string, string>);
            PyLike.Range(start).ForEach(i => Expect(target[i]).To.Equal(defaultValue));
            PyLike.Range(start + items.Length, arraySize).ForEach(
                i => Expect(target[i]).To.Equal(defaultValue));
            items.ForEach(i => Expect(target).To.Contain.Exactly(1).Equal.To(i));
        }

        [Test]
        public void Count_ShouldReturnActualCount()
        {
            // Arrange
            var sut = Create<string, bool>();
            var items = RandomValueGen.GetRandomArray<KeyValuePair<string, bool>>();
            items.ForEach(sut.Add);

            // Pre-assert

            // Act
            var result = sut.Count;

            // Assert
            Expect(result).To.Equal(items.Length);
        }

        [Test]
        public void IsReadonly_ShouldReturnFalse()
        {
            // Arrange
            var sut = Create<int, bool>();

            // Pre-assert

            // Act
            var result = sut.IsReadOnly;

            // Assert
            Expect(result).To.Be.False();
        }

        [Test]
        public void Keys_ShouldReturnKnownKeys()
        {
            // Arrange
            var items = RandomValueGen.GetRandomArray<KeyValuePair<string, string>>();
            var sut = Create<string, string>();
            items.ForEach(sut.Add);

            // Pre-assert

            // Act
            var result = sut.Keys;

            // Assert
            // TODO: swap out with To.Be.Equivalent.To() when the syntax is available in NExpect
            Assert.That(result, Is.EquivalentTo(items.Select(i => i.Key)));
        }

        [Test]
        public void Values_ShouldReturnKnownValues()
        {
            // Arrange
            var items = RandomValueGen.GetRandomArray<KeyValuePair<string, string>>();
            var sut = Create<string, string>();
            items.ForEach(sut.Add);

            // Pre-assert

            // Act
            var result = sut.Values;

            // Assert
            // TODO: swap out with To.Be.Equivalent.To() when the syntax is available in NExpect
            Assert.That(result, Is.EquivalentTo(items.Select(i => i.Value)));
        }

        [Test]
        public void IndexFetch_WithSmartResolver_ShouldReturnExpectedValue()
        {
            // Arrange
            var sut = new DefaultDictionary<string, string>(s => s + "moo");
            var index = RandomValueGen.GetRandomString();
            var expected = index + "moo";
            // Pre-Assert
            // Act
            var result = sut[index];
            // Assert
            Expect(result).To.Equal(expected);
        }

        [Test]
        public void ShouldAppearToBeCaseInsensitiveByDefault()
        {
            // Arrange
            var dict = new DefaultDictionary<string, object>();
            // Pre-Assert
            // Act
            var result = dict.GetPropertyValue("Comparer");
            // Assert
            Expect(result).To.Equal(StringComparer.OrdinalIgnoreCase);
        }

        [Test]
        public void ShouldBeAbleToSpecifyKeyComparer()
        {
            // Arrange
            var dict = new DefaultDictionary<string, object>(
                () => null,
                StringComparer.Ordinal
            );
            // Act
            dict["Foo"] = "foo";
            dict["foo"] = "bar";
            // Assert
            Expect(dict as IDictionary<string, object>)
                .To.Contain.Only(2).Items();
        }

        [Test]
        public void ShouldOptionallyStoreResolvedValuesForLaterReUse()
        {
            // Arrange
            var dict = new DefaultDictionary<string, Dictionary<string, string>>(
                () => new Dictionary<string, string>(),
                storeResolvedDefaults: true
            );
            var level1 = GetRandomString(10);
            var level2 = GetRandomString(10);
            var expected = GetRandomString(10);

            // Act
            dict[level1][level2] = expected;

            // Assert
            Expect(dict[level1][level2])
                .To.Equal(expected);
        }

        private IDictionary<TKey, TValue> Create<TKey, TValue>(
            Func<TValue> defaultResolver = null
        )
        {
            return defaultResolver == null
                ? new DefaultDictionary<TKey, TValue>()
                : new DefaultDictionary<TKey, TValue>(
                    defaultResolver
                );
        }
    }
}

redpajama_set_name: RedPajamaGithub


text:
calysto
=======

[![Gitter](https://badges.gitter.im/Calysto/calysto.svg)](https://gitter.im/Calysto/calysto?utm_source=badge&utm_medium=badge&utm_campaign=pr-badge) [![Travis](https://travis-ci.org/Calysto/calysto.svg?branch=master)](https://travis-ci.org/Calysto/calysto/) [![PyPI version](https://badge.fury.io/py/calysto.svg)](https://badge.fury.io/py/calysto)

Libraries and Languages for Python and Jupyter

Homepage: http://calysto.github.io/

```shell
$ pip install calysto

OR

$ pip3 install calysto
```

You may also need to install:

* libcairo2
* libXrender
* libfontconfig

On MacOS for graphics, you may also need:

* `brew install cairo`


text:
<?php
define('path', '../../../');
$page = "Delete User";
include path.'inc/init.php';
$user = new User();
if(!$user->exist() || !$user->hasPermission("Admin")){
	Redirect::to(path.'index.php');
}
if(Input::exists('get') && Input::get('uid')){
	$user2 = new User(Input::get('uid'));
	if(!$user2->exist()){
		session::flash('error', 'The user does not exists!');
		Redirect::to(path.'index.php');
	}
}else{
	session::flash('error', 'The user does not exists!');
	Redirect::to(path.'index.php');
}
if(Input::exists()){
	if(Token::check(Input::get('token'))){
		$val = new Validation();
		$val->check($_POST, array(
			'id'=> array(
				'required' => true,
			),
		));
		if($val->passed()){
			try {
				$user2->deleteUser(Input::get('id'));
				session::flash('complete','You deleted '.$user2->data()->name);
				Redirect::to(path.'index.php');
			}catch (Exception $e){
				session::flash('error', $e->getMessage());
				Redirect::to(path.'index.php');
			}
		}
	}
}
?>

		<?php include path.'assets/php/css.php';?>

		<?php include path.'assets/php/nav.php';?>

			<form action="" method="post">

Are you sure you want to delete <?php echo $user2->data()->name;?>?

					<input type="submit" class="btn btn-danger" placeholder="confirm" id="confirm">
					Decline

			<input type="hidden" name="token" value="<?php echo Token::generate();?>">
			<input type="hidden" name="id" value="<?php echo Input::get('uid');?>">
			</form>

		<?php include path.'assets/php/js.php'?>


text:
package edu.common.dynamicextensions.entitymanager;

import edu.common.dynamicextensions.util.global.Constants;
import edu.common.dynamicextensions.util.global.Variables;

/**
 * This class returns the queryBuilder depending on the database
 * @author Rahul Ner
 *
 */
public class QueryBuilderFactory
{

	/**
	 * Instance of database specific query builder.
	 */
	private static DynamicExtensionBaseQueryBuilder queryBuilder = null;

	/**
	 * This method returns the query builder depending on the database
	 * @return
	 */
	public static DynamicExtensionBaseQueryBuilder getQueryBuilder()
	{
		if (queryBuilder != null)
		{
			return queryBuilder;
		}

		if (Variables.databaseName.equalsIgnoreCase(Constants.MYSQL_DATABASE))
		{
			queryBuilder = new DynamicExtensionMySQLQueryBuilder();
		}
		else if (Variables.databaseName.equalsIgnoreCase(Constants.ORACLE_DATABASE))
		{
			queryBuilder = new DynamicExtensionOracleQueryBuilder();
		}
		else if (Variables.databaseName.equalsIgnoreCase(Constants.POSTGRESQL_DATABASE))
		{
			queryBuilder = new DynamicExtensionPostGreSQLQueryBuilder();
		}
		return queryBuilder;
	}

}


text:
package org.path.episample.android.logic;

import java.io.File;
import java.util.Date;

import org.path.common.android.provider.FormsColumns;
import org.path.common.android.utilities.ODKDatabaseUtils;
import org.path.common.android.utilities.ODKFileUtils;

import android.content.ContentResolver;
import android.database.Cursor;
import android.net.Uri;

/**
 * Basic definitions of the current form being processed.
 *
 * @author mitchellsundt@gmail.com
 *
 */
public class FormIdStruct {
  public final Uri formUri;
  public final File formDefFile;
  public final String formPath;
  public final String formId;
  public final String tableId;
  public final String appName;
  public final String formVersion;
  public final Date lastDownloadDate;

  public FormIdStruct(Uri formUri, File formDefFile, String formPath, String formId,
      String formVersion, String tableId, Date lastModifiedDate) {
    this.appName = FormsColumns.extractAppNameFromFormsUri(formUri);
    this.formUri = formUri;
    this.formDefFile = formDefFile;
    this.formPath = formPath;
    this.formId = formId;
    this.formVersion = formVersion;
    this.tableId = tableId;
    this.lastDownloadDate = lastModifiedDate;
  }

  public FormIdStruct(FormIdStruct original) {
    this.formUri = original.formUri;
    this.formDefFile = original.formDefFile;
    this.formPath = original.formPath;
    this.formId = original.formId;
    this.tableId = original.tableId;
    this.appName = original.appName;
    this.formVersion = original.formVersion;
    this.lastDownloadDate = original.lastDownloadDate;
  }

  public static final FormIdStruct retrieveFormIdStruct(ContentResolver resolver, Uri formUri) {
    if (formUri == null) {
      return null;
    }
    String appName = FormsColumns.extractAppNameFromFormsUri(formUri);
    Cursor c = null;
    try {
      c = resolver.query(formUri, null, null, null, null);
      if (c != null && c.getCount() == 1) {
        int appRelativeFormMedia = c.getColumnIndex(FormsColumns.APP_RELATIVE_FORM_MEDIA_PATH);
        int formPath = c.getColumnIndex(FormsColumns.FORM_PATH);
        int formId = c.getColumnIndex(FormsColumns.FORM_ID);
        int formVersion = c.getColumnIndex(FormsColumns.FORM_VERSION);
        int tableId = c.getColumnIndex(FormsColumns.TABLE_ID);
        int date = c.getColumnIndex(FormsColumns.DATE);

        c.moveToFirst();

        File formMediaDirectory = ODKFileUtils.asAppFile(appName, ODKDatabaseUtils.get().getIndexAsString(c, appRelativeFormMedia));
        File formDefJsonFile = new File(formMediaDirectory, ODKFileUtils.FORMDEF_JSON_FILENAME);

        Long timestamp = ODKDatabaseUtils.get().getIndexAsType(c, Long.class, date);
        FormIdStruct newForm = new FormIdStruct(formUri, formDefJsonFile,
            ODKFileUtils.getRelativeFormPath(appName, formDefJsonFile), ODKDatabaseUtils.get().getIndexAsString(c, formId),
            ODKDatabaseUtils.get().getIndexAsString(c, formVersion), ODKDatabaseUtils.get().getIndexAsString(c, tableId),
            (timestamp == null) ? null : new Date(timestamp));
        return newForm;
      }
    } finally {
      if (c != null) {
        c.close();
      }
    }
    return null;
  }
}


text:
using Hopnscotch.Portal.Contracts;

namespace Hopnscotch.Portal.Data
{
    internal sealed class AttendanceDbContextFactory : IAttendanceDbContextFactory
    {
        private readonly AttendanceDbContext _context;

        public AttendanceDbContextFactory(IConfig config)
        {
            _context = new AttendanceDbContext();
            _context.Database.Connection.ConnectionString = config.DbConnectionString;
            // _context.Configuration.ProxyCreationEnabled = false;
            //_context.Configuration.LazyLoadingEnabled = false;
            // _context.Configuration.ValidateOnSaveEnabled = false;
        }

        public AttendanceDbContext GetContext()
        {
            return _context;
        }
    }
}


text:
import { expect } from "chai";

import { Formatter } from "@export/formatter";
import { MathSubScriptProperties } from "./math-sub-script-function-properties";

describe("MathSubScriptProperties", () => {
    describe("#constructor()", () => {
        it("should create a MathSubScriptProperties with correct root key", () => {
            const mathSubScriptProperties = new MathSubScriptProperties();

            const tree = new Formatter().format(mathSubScriptProperties);
            expect(tree).to.deep.equal({
                "m:sSubPr": {},
            });
        });
    });
});


text:
import {createSelector} from 'reselect'
import {footageSelector} from './footages'
import {dispTimeSelector} from './disp-time'
import {IFootage} from '../types'

/**
 * Select the footage object to be displayed.
 * Can select null.
 */
export const dispFootageSelector = createSelector(
  dispTimeSelector,
  footageSelector,
  (dispTime: number, footages: IFootage[]): IFootage | null => {
    if (!dispTime) {
      return footages[footages.length - 1] || null
    }
    return footages.find(el => el.time === dispTime) || null
  }
)


text:
import os
from typing import Tuple, Union

import pandas as pd

from ludwig.constants import SPLIT

class CSVLoadMixin:
    """Reads a CSV file into a Pandas DataFrame."""

    config: dict
    processed_dataset_path: str

    def load_processed_dataset(self, split) -> Union[pd.DataFrame,
                                                     Tuple[pd.DataFrame,
                                                           pd.DataFrame,
                                                           pd.DataFrame]]:
        """Loads the processed CSV into a dataframe.

        :param split: Splits along 'split' column if present
        :returns: A pandas dataframe
        """
        dataset_csv = os.path.join(self.processed_dataset_path,
                                   self.csv_filename)
        data_df = pd.read_csv(dataset_csv)
        if SPLIT in data_df:
            data_df[SPLIT] = pd.to_numeric(data_df[SPLIT])
        if split:
            if SPLIT in data_df:
                training_set = data_df[data_df[SPLIT] == 0]
                val_set = data_df[data_df[SPLIT] == 1]
                test_set = data_df[data_df[SPLIT] == 2]
                return training_set, test_set, val_set
            else:
                raise ValueError("The dataset does not have splits, "
                                 "load with `split=False`")
        return data_df

    @property
    def csv_filename(self):
        return self.config["csv_filename"]


text:
With Nix it's possible to quickly and reliably recreate the full environments
for developing, testing and building PostgREST.

## Getting started with Nix

You'll need to [get Nix](https://nixos.org/download.html). The installer will
create your Nix store in the `/nix/` directory, where all build artifacts and
their dependencies will be stored. It will also link the Nix executables like
`nix-env`, `nix-build` and `nix-shell` into your PATH. Nix will manage all
other PostgREST dependencies from here on out. To clean up older build
artifacts from the `/nix/store`, you can run `nix-collect-garbage`.

If you are on a system that does not support nix, for example Windows, you can
run the nix development environment in a docker container. Inside the `nix/`
directory run `docker-compose run --rm nix` to start the docker container. This
will set up the binary cache and launch `nix-shell` automatically.

## Building PostgREST

To build PostgREST from your local checkout of the repository, run:

```bash
nix-build --attr postgrestPackage

```

This will create a `result` directory that contains the PostgREST binary at
`result/bin/postgrest`. The `--attr` parameter (or short: `-A`) tells Nix to
build the `postgrestPackage` attribute from the Nix expression it finds in our
`default.nix` (see below for details). Nix will take care of getting the right
GHC version and all the build dependencies.

## Binary cache

We recommend that you use the PostgREST binary cache on
[cachix](https://cachix.org/):

```bash
# Install cachix:
nix-env -iA cachix -f https://cachix.org/api/v1/install

# Set cachix up to use the PostgREST binary cache:
cachix use postgrest

```

Without cachix, your machine will have to rebuild all the dependencies that are
derived on top of `Musl` for the static builds, which can take a very long time.

## Developing

A development environment for PostgREST is available with `nix-shell`. The
following command will put you into a new shell that has GHC and Cabal on the
PATH:

```bash
nix-shell

```

Within `nix-shell`, you can run Cabal commands as usual. You can also run
stack with the `--nix` option, which causes stack to pick up the non-Haskell
dependencies from the same pinned Nixpkgs version that the Nix builds use.

## Working with `nix-shell` and the PostgREST utility scripts

The PostgREST utilities available in `nix-shell` all have names that begin with
`postgrest-`, so you can use tab completion (typing `postgrest-` and pressing
`<tab>`) in `nix-shell` to see all that are available:

```bash
# Note: The utilities listed here might not be up to date.
[nix-shell]$ postgrest-<tab>
postgrest-build                   postgrest-test-spec
postgrest-check                   postgrest-watch
postgrest-clean                   postgrest-with-all
postgrest-coverage                postgrest-with-postgresql-10
postgrest-lint                    postgrest-with-postgresql-11
postgrest-run                     postgrest-with-postgresql-12
postgrest-style                   postgrest-with-postgresql-13
postgrest-style-check             postgrest-with-postgresql-9.6
postgrest-test-io
...

[nix-shell]$

```

Some additional modules like `memory`, `docker` and `release`
have large dependencies that would need to be built before the shell becomes
available, which could take an especially long time if the cachix binary cache
is not used. You can activate those by passing a flag to `nix-shell` with
`nix-shell --arg <module> true`. This will make the respective utilites available:

```bash
$ nix-shell --arg memory true
[nix-shell]$ postgrest-<tab>
postgrest-build                   postgrest-test-spec
postgrest-check                   postgrest-watch
postgrest-clean                   postgrest-with-all
postgrest-coverage                postgrest-with-postgresql-10
postgrest-lint                    postgrest-with-postgresql-11
postgrest-run                     postgrest-with-postgresql-12
postgrest-style                   postgrest-with-postgresql-13
postgrest-style-check             postgrest-with-postgresql-9.6
postgrest-test-io
postgrest-test-memory
...

```

Note that `postgrest-test-memory` is now also available.

To run one-off commands, you can also use `nix-shell --run <command>`, which
will lauch the Nix shell, run that one command and exit. Note that the tab
completion will not work with `nix-shell --run`, as Nix has yet to evaluate
our Nix expressions to see which utilities are available.

```bash
$ nix-shell --run postgrest-style

# Note that you need to quote any arguments that you would like to pass to
# the command to be run in nix-shell:
$ nix-shell --run "postgrest-foo --bar"

```

A third option is to install utilities that you use very often locally:

```bash
$ nix-env -f default.nix -iA devTools

# `postgrest-style` can now be run directly:
$ postgrest-style

```

If you use `nix-shell` very often, you might like to use
https://github.com/xzfc/cached-nix-shell, which skips evaluating all our Nix
expressions if nothing changed, reducing startup time for the shell
considerably.

Note: Once inside nix-shell, the utilities work from any directory inside
the PostgREST repo. Paths are resolved relative to the repo root:

```bash
$ cd src
# Even though the current directory is ./src, the config path must still start
# from the repo root:
$ postgrest-run test/io/configs/simple.conf
```

## Testing

In nix-shell, you'll find utility scripts that make it very easy to run our
test suite, including setting up all required dependencies and
temporary test databases:

```bash
# Run the tests against the most recent version of PostgreSQL:
$ nix-shell --run postgrest-test-spec

# Run the tests against all supported versions of PostgreSQL:
$ nix-shell --run "postgrest-with-all postgrest-test-spec"

# Run the tests against a specific version of PostgreSQL (use tab-completion in
# nix-shell to see all available versions):
$ nix-shell --run "postgrest-with-postgresql-13 postgrest-test-spec"

```

The io-test that test PostgREST as a black box with inputs and outputs can be
run with `postgrest-test-io`. The test runner under the hood is
[pytest](https://docs.pytest.org/) and you can pass it the usual options:

```bash
# Filter the tests to run by name, including all that contain 'config':
postgrest-test-io -k config

# Run tests in parallel using xdist, specifying the number of processes:
postgrest-test-io -n auto
postgrest-test-io -n 8
```

The memory tests check that we don't surpass a memory threshold for big request bodies.

```bash
# Build the dependencies needed for the memory test
nix-shell --arg memory true

# Run the memory test
postgrest-test-memory
```

The loadtests ensure that performance doesn't drop on a change. Underlyingly they use
[vegeta](https://github.com/tsenart/vegeta).

```bash
# Run the loadtests on the latest commit(HEAD)
postgrest-loadtest

# You can loadtest comparing to a different branch
postgrest-loadtest-against master

# Produce a markdown report to be used on CI
postgrest-loadtest-report
```

Our query cost tests ensure that our generated queries don't surpass a threshold EXPLAIN cost.

```bash
postgrest-test-querycost
```

doctests for some of our modules are also available:

```bash
postgrest-test-doctest
```

## Code coverage

Code coverage is available under the `postgrest-coverage` command. This will produce a `./coverage` directory that can be visualized with a simple http server.

```bash
# Will run all the tests and produce a coverage dir
postgrest-coverage

# Visualize the output
cd coverage
python -mSimpleHTTPServer 8080
```

## Linting and styling code

The nix-shell also contains scripts for linting and styling the PostgREST
source code:

```bash
# Linting
$ nix-shell --run postgrest-lint

# Styling / auto-formatting code
$ nix-shell --run postgrest-style

```

There is also `postgrest-style-check` that exits with a non-zero exit code if
the check resulted in any uncommited changes. It's mostly useful for CI.

## General development tools

Tools like `postgrest-build`, `postgrest-run` etc. are simple wrappers around
`cabal` and should do what you expect. `postgrest-check` runs most checks that will
also run in CI, with the exception of the IO and Memory checks that need to be run
separately.

`postgrest-with-postgresql-*` take a command as an argument and will run it
with a temporary database. `postgrest-with-all` will run the command against
all supported PostgreSQL versions. Tests run without `postgrest-with-*` are
run against the latest PostgreSQL version by default.

`postgrest-watch` takes a command as an argument that it will re-run if any source
file is changed. For example, `postgrest-watch postgrest-with-all postgrest-test-spec`
will re-run the full spec test suite against all PostgreSQL versions on every change.

## Tour

The following is not required for working on PostgREST with Nix, but it will
give you some more background and details on how it works.

### `default.nix`

[`default.nix`](../default.nix) is our 'repository expression' that pulls all
the pieces that we define with Nix together. It returns a set (like a dict in
other programming languages), where each attribute is a derivation that Nix
knows how to build, like the `postgrest` attribute from earlier.

Internally, our `default.nix` uses the `pkgs.callPackage` function to import
the modules that we defined in the `nix` directory. It automatically passes the
arguments those modules require if they are available in `pkgs` (this means
that `pkgs` is defined in terms of itself, better not to think too much about
that).

We also use `default.nix` to load our pinned version of the `nixpkgs`
repository. This set of packages will always be the same, independently from
where or when you use it. The pinned version can be upgraded with the small
`nixpkgs-upgrade` utility. Running `nixpkgs-upgrade > nix/nixpkgs-version.nix`
in `nix-shell` will upgrade the pinned version to the latest `nixpkgs-unstable`
version.

### `shell.nix`

[`shell.nix`](../shell.nix) defines an environment in which PostgREST can be
built and developed. It extends the build enviroment from our `postgrest`
attribute with useful utilities that will be put on the PATH in `nix-shell`.

### `nix/overlays`

Our overlays to the Nix package set are defined here. They allow us to tweak our
`pkgs` in `default.nix` by adding new packages or overriding existing ones.

## Upgrading dependencies

See the [upgrading checklist](UPGRADE.md) for how to upgrade the PostgREST
dependencies.


text:
"use strict";
var PromiseCompleter = (function () {
    function PromiseCompleter() {
        var _this = this;
        this.promise = new Promise(function (res, rej) {
            _this.resolve = res;
            _this.reject = rej;
        });
    }
    return PromiseCompleter;
}());
exports.PromiseCompleter = PromiseCompleter;
//# sourceMappingURL=/usr/local/google/home/jelbourn/material2/tmp/broccoli_type_script_compiler-input_base_path-OxHzApZr.tmp/0/core/async/promise-completer.js.map


text:
package org.blueocean;

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

public class ClientRGAQ {
	/*
	 * generic class represent each element of the square
	 */
	static class Node<T>{
		private T data;

		public Node(T obj){
			this.data = obj;
		}

		public T getData(){
			return data;
		}
	}

	/*
	 * 2D array is a square
	 */
	public static <T> Node<T>[][] to2DArray(T[] input){
		int rowNum = (int) Math.ceil(Math.sqrt(input.length));
		@SuppressWarnings("unchecked")
		Node<T>[][] arrays = new Node[rowNum][rowNum];
		for(int i=0; i<input.length; i++){
			Node<T> node = new Node<T>(input[i]);
			arrays[i/rowNum][i%rowNum] = node;
		}
		return arrays;
	}

	/**
	 * convert 2D array to list
	 *
	 * @param input
	 * @return
	 */
	public static <T> List<T> to1DArray(Node<T>[][] input){
		List<T> resultList = new ArrayList<T>();
		for(int i=0; i<input.length; i++){
			for(int j=0; j<input[i].length; j++)
				if(input[i][j]!=null)
					resultList.add(input[i][j].data);
		}
		return resultList;
	}

}


text:
namespace xLibrary
{
    using Chains.Play.Web;

    public sealed class HttpResultContextWithxContext : HttpResultContextBase<HttpResultContextWithxContext>
    {
        public readonly xContext xContext;

        public HttpResultContextWithxContext(
            xContext xContext, string resultText = "", string contentType = "text/html", int statusCode = 200)
            : base(resultText, contentType, statusCode)
        {
            this.xContext = xContext;
        }

        public HttpResultContextWithxContext(xContext xContext, string statusText, int statusCode)
            : base(statusText, statusCode)
        {
            this.xContext = xContext;
        }

        public HttpResultContextWithxContext(xContext xContext, string redirectTo, bool permanentRedirect)
            : base(redirectTo, permanentRedirect)
        {
            this.xContext = xContext;
        }

        public void ApplyOutputToHttpContext()
        {
            if (this.xContext.ContextInfo.HttpContext != null)
            {
                this.ApplyOutputToHttpContext(this.xContext.ContextInfo.HttpContext);
            }
            else
            {
                this.ApplyOutputToHttpContext(this.xContext.ContextInfo.HttpListenerContext);
            }
        }
    }
}


text:
<?xml version="1.0" encoding="UTF-8"?>
<resources xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:xliff="urn:oasis:names:tc:xliff:document:1.2">
    <string name="app_name" msgid="5934709770924185752">"CaptivePortalLogin"</string>
    <string name="action_use_network" msgid="6076184727448466030">"Dieses Netzwerk im Istzustand verwenden"</string>
    <string name="action_do_not_use_network" msgid="4577366536956516683">"Dieses Netzwerk nicht verwenden"</string>
    <string name="action_bar_label" msgid="917235635415966620">"Im Netzwerk anmelden"</string>
    <string name="ssl_error_warning" msgid="6653188881418638872">"Im Netzwerk, zu dem Sie eine Verbindung herstellen möchten, liegen Sicherheitsprobleme vor."</string>
    <string name="ssl_error_example" msgid="647898534624078900">"Beispiel: Die Log-in-Seite gehört möglicherweise nicht zur angezeigten Organisation."</string>
    <string name="ssl_error_continue" msgid="6492718244923937110">"Trotzdem in einem Browser fortfahren"</string>
</resources>


text:
<?xml version="1.0" encoding="utf-8"?>
<resources>
    <color name="colorPrimary">#42b3e6</color>
    <color name="colorPrimaryDark">#0079f1</color>
    <color name="colorAccent">#FF4081</color>
</resources>


text:
package izzyaxel.arcaneartificing.blocks.functional;

import cpw.mods.fml.relauncher.Side;
import cpw.mods.fml.relauncher.SideOnly;
import izzyaxel.arcaneartificing.blocks.tileEntities.TEGrindstone;
import izzyaxel.arcaneartificing.main.AAReference;
import net.minecraft.block.Block;
import net.minecraft.block.BlockContainer;
import net.minecraft.block.material.Material;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.tileentity.TileEntity;
import net.minecraft.world.World;

public class BlockGrindstone extends BlockContainer
{
	public BlockGrindstone()
	{
		super(Material.piston);
		this.setBlockName("grindstone");
		this.setStepSound(Block.soundTypePiston);
		this.setHardness(1.0F);
		this.setResistance(5.0F);
		this.setBlockTextureName(AAReference.MODID + ":" + getUnlocalizedName().substring(5));
		this.setHarvestLevel("pickaxe", 1);
		this.setBlockBounds(0, 0, 0, 1, 0.6f, 1);
	}

	@Override
	public boolean onBlockActivated(World world, int x, int y, int z, EntityPlayer player, int side, float hitX, float hitY, float hitZ)
	{
		if(world.getTileEntity(x, y, z) instanceof TEGrindstone)
		{
			TEGrindstone grindstone = (TEGrindstone)world.getTileEntity(x, y, z);
			if(!grindstone.isTurning())
			{
				grindstone.setTurning();
				return true;
			}
		}
		return false;
	}

	@Override
	public TileEntity createNewTileEntity(World world, int id)
	{
		return new TEGrindstone();
	}

	@SideOnly(Side.CLIENT)
	@Override
	public int getRenderType()
	{
		return AAReference.grindstoneRenderID;
	}

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

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


text:
<?php
namespace Mystique\Common\Inspector;

use Iterator;

class FilterIterator extends \FilterIterator {
    function __construct(Iterator $iterator, Matcher\MatcherInterface $filter) {
        parent::__construct($iterator);
        $this->filter = $filter;
    }

    final function accept() {
        return $this->filter->match(parent::current());
    }
}


text:
package com.google.code.linkedinapi.schema;

/**
 *
Java class for anonymous complex type.
 *
 *
The following schema fragment specifies the expected content contained within this class.
 *
 *

 * <complexType>
 *   <complexContent>
 *     <restriction base="{http://www.w3.org/2001/XMLSchema}anyType">
 *       <sequence>
 *         <element ref="{}id" minOccurs="0"/>
 *         <element ref="{}first-name"/>
 *         <element ref="{}last-name"/>
 *         <element ref="{}headline"/>
 *         <element ref="{}picture-url"/>
 *       </sequence>
 *     </restriction>
 *   </complexContent>
 * </complexType>
 *

 *
 *
 */
public interface Creator
    extends SchemaEntity
{

    /**
     * Gets the value of the id property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    String getId();

    /**
     * Sets the value of the id property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    void setId(String value);

    /**
     * Gets the value of the firstName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    String getFirstName();

    /**
     * Sets the value of the firstName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    void setFirstName(String value);

    /**
     * Gets the value of the lastName property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    String getLastName();

    /**
     * Sets the value of the lastName property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    void setLastName(String value);

    /**
     * Gets the value of the headline property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    String getHeadline();

    /**
     * Sets the value of the headline property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    void setHeadline(String value);

    /**
     * Gets the value of the pictureUrl property.
     *
     * @return
     *     possible object is
     *     {@link String }
     *
     */
    String getPictureUrl();

    /**
     * Sets the value of the pictureUrl property.
     *
     * @param value
     *     allowed object is
     *     {@link String }
     *
     */
    void setPictureUrl(String value);

}


text:
from toolchain import CythonRecipe

class AudiostreamRecipe(CythonRecipe):
    version = "master"
    url = "https://github.com/kivy/audiostream/archive/{version}.zip"
    library = "libaudiostream.a"
    depends = ["python", "sdl2", "sdl2_mixer"]
    pre_build_ext = True

recipe = AudiostreamRecipe()


text:
'use strict';

var path = require('path');
var fs   = require('fs');

suite('Issues', function () {
  var issues = path.resolve(__dirname, 'issues');

  fs.readdirSync(issues).forEach(function (file) {
    if ('.js' === path.extname(file)) {
      require(path.resolve(issues, file));
    }
  });
});


text:
using System;

namespace Server.Items
{
	public abstract class BaseNecklace : BaseJewel
	{
		public override int BaseGemTypeNumber{ get{ return 1044241; } } // star sapphire necklace

		public BaseNecklace( int itemID ) : base( itemID, Layer.Neck )
		{
		}

		public BaseNecklace( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();
		}
	}

	public class Necklace : BaseNecklace
	{
		[Constructable]
		public Necklace() : base( 0x1085 )
		{
			Weight = 0.1;
		}

		public Necklace( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();
		}
	}

	public class GoldNecklace : BaseNecklace
	{
		[Constructable]
		public GoldNecklace() : base( 0x1088 )
		{
			Weight = 0.1;
		}

		public GoldNecklace( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();
		}
	}

	public class GoldBeadNecklace : BaseNecklace
	{
		[Constructable]
		public GoldBeadNecklace() : base( 0x1089 )
		{
			Weight = 0.1;
		}

		public GoldBeadNecklace( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();
		}
	}

	public class SilverNecklace : BaseNecklace
	{
		[Constructable]
		public SilverNecklace() : base( 0x1F08 )
		{
			Weight = 0.1;
		}

		public SilverNecklace( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();
		}
	}

	public class SilverBeadNecklace : BaseNecklace
	{
		[Constructable]
		public SilverBeadNecklace() : base( 0x1F05 )
		{
			Weight = 0.1;
		}

		public SilverBeadNecklace( Serial serial ) : base( serial )
		{
		}

		public override void Serialize( GenericWriter writer )
		{
			base.Serialize( writer );

			writer.Write( (int) 0 ); // version
		}

		public override void Deserialize( GenericReader reader )
		{
			base.Deserialize( reader );

			int version = reader.ReadInt();
		}
	}
}


text:
/**
 * DRAMsim v2 integration
 * Author: Rio Xiangyu Dong
 *         Tao Zhang
 */

// #define DEBUGI
#define interesting 0x55fc40
// #define interesting_era_l 8429720000
// #define interesting_era_h 8430182001

#include <cstdlib>
#include <iomanip>

#include "mem/DRAMSim2.hh"

std::string
hexstr( int i ){
    std::stringstream s;
    s << "0x" << std::hex << i;
    return s.str();
}

bool
isInteresting(PacketPtr pkt ){
    // bool is_interesting_time =
    //     (curTick() >= interesting_era_l) &&
    //     (curTick() <= interesting_era_h);
    bool is_interesting_addr = (pkt->getAddr() == interesting);
    //return is_interesting_time || is_interesting_addr;
    return is_interesting_addr;
}

DRAMSim2::DRAMSim2(const Params *p) : DRAMSim2Wrapper(p)
{
    warn("This is an integrated DRAMsim v2 module");
    int memoryCapacity = (int)(params()->range.size() / 1024 / 1024);
    std::cout << "device file: " << p->deviceConfigFile << std::endl;
    std::cout << "system file: " << p->systemConfigFile << std::endl;
    std::cout << "output file: " << p->outputFile << std::endl;
    //dramsim2 = new DRAMSim::MultiChannelMemorySystem(p->deviceConfigFile, p->systemConfigFile, p->cwd, p->traceFile, memoryCapacity, "./results/output", NULL, NULL);
    dramsim2 = new DRAMSim::MultiChannelMemorySystem(p->deviceConfigFile,
            p->systemConfigFile, atoi((p->tpTurnLength).c_str()), p->genTrace, p->cwd, p->traceFile,
            memoryCapacity, p->outputFile, NULL, NULL, p->numPids, p->fixAddr, p->diffPeriod, p->p0Period, p->p1Period, p->offset);
    // intentionally set CPU:Memory clock ratio as 1, we do the synchronization later
    dramsim2->setCPUClockSpeed(0);
    num_pids = p->numPids;

    std::cout << "CPU Clock = " << (int)(1000000 / p->cpu_clock) << "MHz" << std::endl;
    std::cout << "DRAM Clock = " << (1000 / tCK) << "MHz" << std::endl;
    std::cout << "Memory Capacity = " << memoryCapacity << "MB" << std::endl;

    DRAMSim::Callback_t *read_cb = new DRAMSim::Callback<DRAMSim2, void, unsigned, uint64_t, uint64_t, uint64_t>(this, &DRAMSim2::read_complete);
    DRAMSim::Callback_t *write_cb = new DRAMSim::Callback<DRAMSim2, void, unsigned, uint64_t, uint64_t, uint64_t>(this, &DRAMSim2::write_complete);
    dramsim2->RegisterCallbacks(read_cb, write_cb, NULL);
}

DRAMSim2 *
DRAMSim2Params::create()
{
    return new DRAMSim2(this);
}

bool
DRAMSim2::MemoryPort::recvTimingReq(PacketPtr pkt)
{
    memory->tracePrinter->addTrace( pkt, "recvTimingReq" );
    /* I don't know when they can remove this... */
    /// @todo temporary hack to deal with memory corruption issue until
    /// 4-phase transactions are complete. Remove me later
    //cout << "Cycle: " << dramsim2->currentClockCycle << " Receive Timing Request" << endl;
    this->removePendingDelete();

    DRAMSim2* dram = dynamic_cast<DRAMSim2*>(memory);
    bool retVal = false;

    // if DRAMSim2 is disabled, just use the default recvTiming.
    if( !dram ) {
        memory->updateDRAMSim2();
        return SimpleTimingPort::recvTimingReq(pkt);
    } else {
#ifdef DEBUGI
        if( isInteresting( pkt ) ){
            printf( "(%8s)[%lu] using dramsim recvTiming\n",
               hexstr( pkt->getAddr() ).c_str(),
                    pkt->threadID
               );
        }
#endif
        if (pkt->memInhibitAsserted()) {
            // snooper will supply based on copy of packet
            // still target's responsibility to delete packet
            delete pkt;
            memory->updateDRAMSim2();
            return true;
        }

        uint64_t addr = pkt->getAddr();
        AccessMetaInfo meta;
        meta.pkt = pkt;
        meta.port = this;
        TransactionType transType;

        memory->updateDRAMSim2();

        if (pkt->needsResponse()) {
#ifdef DEBUGI
            if( isInteresting( pkt ) ){
                printf( "(%8s)[%lu] interesting needs response\n",
                        hexstr( pkt->getAddr() ).c_str(),
                        pkt->threadID
                        );
            }
#endif
            if (pkt->isRead()) {
                transType = DATA_READ;
            } else if (pkt->isWrite()) {
                transType = DATA_WRITE;
            } else {
                // only leverage the atomic access to move data, don't use the
                // latency
                //std::cout << "case 1" << std::endl;
                dram->doAtomicAccess(pkt);
                assert(pkt->isResponse());
                schedTimingResp(pkt, curTick() + 1, pkt->threadID);
                memory->updateDRAMSim2();
                return true;
            }

            // record the READ/WRITE request for later use
	    uint64_t index = addr << 1;
            if (transType == DATA_WRITE)
                index = index | 0x1;
            dram->ongoingAccess.insert(make_pair(index, meta));
            uint64_t threadID = pkt->threadID;
            // For trace generation
            if (threadID >= dram->num_pids){
                fprintf( stderr,"warn: gem5 made a trans for a packet with threadID >= dram->numpids\n" );
                threadID = 0;
            }

#ifdef DEBUGI
            if( isInteresting( pkt ) ){
                printf( "(%8s)[%lu] made interesting trans: g5 time %lu / d2 time %lu\n",
                        hexstr( pkt->getAddr() ).c_str(),
                        pkt->threadID,
                        curTick(), dramsim2->currentClockCycle );
            }
#endif
            Transaction tr = Transaction(transType, addr, NULL, threadID,
                    dramsim2->currentClockCycle, 0);
            retVal = dramsim2->addTransaction(tr);
            //std::cout << "case 2" << std::endl;
            //std::cout << "Thread: " << threadID << std::endl;
            //std::cout << "Addr  : " << std::hex << setfill('0') << setw(8) << addr << std::endl;
        } else {
            if (pkt->isWrite()) {	// write-back does not need a response, but DRAMsim2 needs to track it
                transType = DATA_WRITE;
                uint64_t threadID = pkt->threadID;
                // For trace generation
            	if (threadID >= dram->num_pids) {
                    fprintf( stderr,"warn: gem5 made a trans for a packet with threadID >= dram->numpids\n" );
                    threadID = 0;
                }
#ifdef DEBUGI
                if( isInteresting( pkt ) ){
                    printf( "(%8s)[%lu] made interesting trans: g5 time %lu / d2 time %lu\n",
                            hexstr( pkt->getAddr() ).c_str(),
                            pkt->threadID,
                            curTick(), dramsim2->currentClockCycle );
                }
#endif
                Transaction tr = Transaction(transType, addr, NULL, threadID,
                        dramsim2->currentClockCycle, 0);
                retVal = dramsim2->addTransaction(tr);
                if (retVal == true) {
                	dram->doAtomicAccess(pkt);
                	this->addPendingDelete(pkt);
                }
                //std::cout << "case 3" << std::endl;
                // assert(retVal == true);
            }
            else {
            	//std::cout << "case 4" << std::endl;
				retVal = dram->doAtomicAccess(pkt);

				// Again, I don't know....
				/// @todo nominally we should just delete the packet here.
				/// Until 4-phase stuff we can't because the sending
				/// cache is still relying on it
				this->addPendingDelete(pkt);
			}
        }
    }
    memory->updateDRAMSim2();
    return retVal;
}

void DRAMSim2::read_complete(unsigned id, uint64_t address, uint64_t clock_cycle, uint64_t threadID)
{
	//printf("read complete for %llx @ cycle %llu\n", address, clock_cycle);
    uint64_t index = address << 1;
    if (ongoingAccess.count(index)) {
        AccessMetaInfo meta = ongoingAccess.find(index)->second;
        PacketPtr pkt = meta.pkt;
        DRAMSim2::MemoryPort *my_port = (DRAMSim2::MemoryPort*)(meta.port);

        my_port->removePendingDelete();

        if (pkt->needsResponse()) {
            doAtomicAccess(pkt);
            assert(pkt->isResponse());

            // remove the skew between DRAMSim2 and gem5
            Tick toSchedule = (Tick)(clock_cycle+1) * (Tick)(tCK * 1000);
#ifdef DEBUGI
            if( isInteresting( pkt ) ){
                printf( "(%8s)[%lu] toSchedule interesting before calc %lu\n SimClock %lu\n curTick %lu\n",
                        hexstr( pkt->getAddr() ).c_str(),
                        pkt->threadID,
                        toSchedule,
                        SimClock::Int::ms,
                        curTick()
                        );
            }
#endif
            if (toSchedule <= curTick()){
#ifdef DEBUGI
                  if ( isInteresting( pkt ) ){
                      printf( "(%8s) (1) taken\n",
                           hexstr( pkt->getAddr() ).c_str() );
                  }
#endif
                  toSchedule = curTick() + 1;  //not accurate, but I have to
            }
            if (toSchedule >= curTick() + SimClock::Int::ms){
#ifdef DEBUGI
                  if ( isInteresting( pkt ) ){
                      printf( "(%8s) (2) taken\n",
                           hexstr( pkt->getAddr() ).c_str() );
                  }
#endif
                  toSchedule = curTick() + SimClock::Int::ms - 1; //not accurate
            }
#ifdef DEBUGI
            if( isInteresting( pkt ) ){
                printf( "(%8s) toSchedule interesting after calc %lu\n",
                        hexstr( pkt->getAddr() ).c_str(),
                        toSchedule );
            }
#endif
            my_port->schedTimingResp(pkt, toSchedule, threadID);
            tracePrinter->addTrace( pkt, "read_complete", toSchedule );
        } else {
            my_port->addPendingDelete(pkt);
        }
        ongoingAccess.erase(ongoingAccess.find(index));
    }
}

void DRAMSim2::write_complete(unsigned id, uint64_t address, uint64_t clock_cycle, uint64_t threadID)
{
    uint64_t index = address << 1;
    index = index | 0x1;
    if (ongoingAccess.count(index)) {
        AccessMetaInfo meta = ongoingAccess.find(index)->second;
        PacketPtr pkt = meta.pkt;
        DRAMSim2::MemoryPort *my_port = (DRAMSim2::MemoryPort*)(meta.port);

        my_port->removePendingDelete();

        if (pkt->needsResponse()) {
            doAtomicAccess(pkt);
            assert(pkt->isResponse());
            Tick toSchedule = (Tick)(clock_cycle) * (Tick)(tCK * 1000);
#ifdef DEBUGI
            // if( isInteresting( pkt ) ){
            //     printf( "toSchedule interesting before calc %lu\n", toSchedule );
            // }
#endif
            if (toSchedule <= curTick())
                  toSchedule = curTick() + 1;  //not accurate, but I have to
            if (toSchedule >= curTick() + SimClock::Int::ms)
                  toSchedule = curTick() + SimClock::Int::ms - 1; //not accurate
#ifdef DEBUGI
            // if( isInteresting( pkt ) ){
            //     printf( "toSchedule interesting after calc %lu\n", toSchedule );
            // }
#endif
            my_port->schedTimingResp(pkt, toSchedule, threadID);
            tracePrinter->addTrace( pkt, "write_complete", toSchedule );
        } else {
            my_port->addPendingDelete(pkt);
        }
        ongoingAccess.erase(ongoingAccess.find(index));
    }
}

void DRAMSim2::report_power(double a, double b, double c, double d)
{
}


text:
//
//  UIButton+SkinParser.h
//  EALayout
//
//  Created by easycoding on 15/7/17.
//  Copyright (c) 2015年 www.easycoding.top. All rights reserved.
//

#ifndef __UIBUTTON_SKINPARSER_H__
#define __UIBUTTON_SKINPARSER_H__

#import <Foundation/Foundation.h>
#import "SkinParser.h"

/**
 @brief 建议直接使用  EAButton, 在完整版里会有自定义控件EAButton,比UIButton更好用
 */
@interface UIButton(SkinParser)

/**
 @key[String]:image
 @value[Dictionary/String]:不同状态对应图片
 @brief Dictionary:状态包含["normal", "highlighted", "disabled", "selected"],
        String: 相当于设置 "normal" 状态对应图片
 @example
        Dictionary :
        "image":{
            "normal":"mytestImage/normal.png",
            "selected":"selected.png"
        }
        String:  "image":"mytestImage/normal.png"
 */
DefineParseFun(image);

/**
 @key[String]:backgroundImage
 @value[Dictionary/String]:不同状态对应背景图片
 @brief Dictionary:状态包含["normal", "highlighted", "disabled", "selected"],
        String: 相当于设置 "normal" 状态对应背景图片
 @example
        Dictionary :
        "backgroundImage":{
            "normal":"mytestImage/normalbackgroundImage.png",
            "selected":"selectedbackgroundImage.png"
        }
        String:  "backgroundImage":"mytestImage/normalbackgroundImage.png"
 */
DefineParseFun(backgroundImage);

/**
 @key[String]:title
 @value[Dictionary/String]:不同状态对应文字
 @brief Dictionary:状态包含["normal", "highlighted", "disabled", "selected"],
        String: 相当于设置 "normal" 状态对应文字
 @example
        Dictionary :
        "title":{
            "normal":"titlenormal",
            "selected":"titlehighlighted"
        }
        String:  "title":"titlenormal"
 */
DefineParseFun(title);

/**
 @key[String]:titleColor
 @value[Dictionary/Color]:不同状态对应文字颜色
 @brief Dictionary:状态包含["normal", "highlighted", "disabled", "selected"],
        String: 相当于设置 "normal" 状态对应文字颜色
 @example
        Dictionary :
        "titleColor":{
            "normal":"blueColor",
            "selected":[255,0,0],
        }
        Color:  "titleColor":[0,0,255,0.5]
 */
DefineParseFun(titleColor);

/**
 @key[String]:titleShadowColor
 @value[Dictionary/Color]:不同状态对应文字阴影颜色
 @brief Dictionary:状态包含["normal", "highlighted", "disabled", "selected"],
 String: 相当于设置 "normal" 状态对应文字阴影颜色
 @example
        Dictionary :
        "titleShadowColor":{
            "normal":"blueColor",
            "selected":[255,0,0],
        }
        Color:  "titleShadowColor":[0,0,255,0.5]
 */
DefineParseFun(titleShadowColor);

/**
 @key[String]:text
 @value[String]: button normal状态对应文字
 @brief title的简写,为了兼容UILabel设置文字的使用习惯
 @example "text":"I am normal title"
 */
- (void)setText:(NSString*)str;

/**
 @key[String]:textColor
 @value[Color]: button normal状态对应文字颜色
 @brief titleColor的简写,为了兼容UILabel设置文字颜色的使用习惯
 @example "titleColor":"#FFFF0000"
 */
- (void)setTextColor:(UIColor*)color;

@end

#endif //__UIBUTTON_SKINPARSER_H__


text:
"use strict";
var AdpPretifier = (function() {

    var isNodeType = function (str){
        return str.includes("sc_req") || str.includes("seaclouds.nodes") && !isLocationType(str);
    }

    var isLocationType = function(str){
        return str.includes("seaclouds.Nodes.Compute") || str.includes("seaclouds.Nodes.Platform");
    }

    var findLocationByName = function(location, index, array){
        return this == location.name;
    }

    if(!log){
        throw "AdpPrettifier requires loglevel.js"
    }

    if(!jsyaml){
        throw "AdpPrettifier requires JS-YAML"
    }
    var adpToObject = function(adp){
        var jsAdp = jsyaml.safeLoad(adp);
        var application = {
            name: undefined,
            locations: []
        };

        application.name = jsAdp.description;
        var services = [];

        // Not sure about how to deal with Camel Case agains the tosca underscore pattern, should I mix it?
        if(jsAdp.topology_template && jsAdp.topology_template.node_templates){

            var nodeTemplates = jsAdp.topology_template.node_templates;

            // node_templates are not a list of nodes but an object with several properties. This way iterates thought properties
            for (var nodeTemplateKey in nodeTemplates) {
                if (!nodeTemplates.hasOwnProperty(nodeTemplateKey)) {
                    //The current property is not a direct property of jsAdp.topology_template.node_templates
                    continue;
                }

                var nodeTemplate = nodeTemplates[nodeTemplateKey];

                if(isLocationType(nodeTemplate.type)){
                    // If it's a location we add an empty list of hosted services and we add into the application topology
                    nodeTemplate.name = nodeTemplateKey;
                    nodeTemplate.services = [];
                    application.locations.push(nodeTemplate);
                }else if (isNodeType(nodeTemplate.type)){
                    // We will add the node_template the de pending work list
                    nodeTemplate.name = nodeTemplateKey;
                    services.push(nodeTemplate);
                }else{
                    log.warn("Unrecognized Node Type");
                    continue;
                }
            }

            services.forEach(function (service){
                if(service.requirements){
                    service.requirements.forEach(function(requirement){
                        if(requirement.host){
                            var location = application.locations.find(findLocationByName, requirement.host);

                            if(!location){
                                // Maybe an exception it's better for this
                                log.warn("The service is hosted on an unknown location, it will be ignored");
                            }else{
                                location.services.push(service);
                            }
                        }
                    });
                }else{
                    // Maybe an exception it's better for this
                    log.warn("The service is has no requirments, it will be ignored. ");
                }

            });

        }

        return application;
    }

    var adpToTopology = function(adp){
        var application = AdpToObject(adp);

        var topology = {
            "nodes": [],
            "links": []
        };

        log.warn("This function is currently unsupported");
        return topology;
    }

    return {
        adpToObject: adpToObject,
        adpToTopology: adpToTopology
    };
})()


text:
{% extends "base.html" %}
{% block pagetitle %}Gestion de configuration{% endblock %}
{% block maintitle %}Liste des sauvegardes {% if archive %}archivées{% endif %}{% endblock %}

{%block navigationButtons%}
{% if not archive %}
A
{%else%}
D
{% endif %}
{%endblock%}

{% block content %}

{% regroup backups by from_envt as envt_list %}

{% for envt in envt_list %}

{{envt.grouper.name}}

		{% for bckset in envt.list %}

			{{bckset.set_date}}

{{ bckset.item_count }} éléments sauvegardés

		{% endfor %}

{% endfor %}

{% endblock content %}


text:
var feed2productModel = {};

//遍历feed2product表
feed2productModel.findAllfeed2product = function(callback) {
	connection.query('select * from feed2product', function (error, results, fields) {
		var resData = {
			code: 0,
			data: {}
		}
		if (error) {
			throw error;
		}else {
			resData.code = 1;
			resData.data = results;
			console.log('The first is: ', results);

		}
		callback(resData);
	});
}

module.exports = feed2productModel;


text:
#ifndef __SKIPLIST_H__
#define __SKIPLIST_H__

#include <stddef.h>

#if defined(__cplusplus)
extern "C" {
#endif

#define SKIPLIST_LEVEL_MAX 32 /* max skiplist level (0~11) */
#define SKIPLIST_FACTOR_P 0.5

#define skiplist(cmp) skiplist_new(cmp)
#define skiplist_height(sl) skiplist_level(sl)
#define skiplist_iter(sl) skiplist_iter_new(sl)
#define skiplist_each(sl, node)                            \
    for ((node) = (sl)->head->forwards[0]; (node) != NULL; \
         (node) = (node)->forwards[0])

/* socre comparator type, return < 0 if arg#0 < arg#1 */
typedef int (*skiplist_cmp_t)(unsigned long score1, unsigned long score2);

enum {
    SKIPLIST_OK = 0,     /* operation is ok */
    SKIPLIST_ENOMEM = 1, /* no memory error */
};

struct skiplist_node {
    unsigned long score;             /* node score */
    void *data;                      /* node data */
    struct skiplist_node **forwards; /* node forward links */
    struct skiplist_node *backward;  /* node backward link */
};

struct skiplist {
    size_t len;                 /* skiplist length */
    int level;                  /* skiplist level */
    struct skiplist_node *head; /* skiplist head */
    struct skiplist_node *tail; /* skiplist tail */
    skiplist_cmp_t cmp;         /* score comparator */
};

struct skiplist_iter {
    struct skiplist *skiplist;  /* skiplist to iterate */
    struct skiplist_node *node; /* current skiplist node */
};

struct skiplist_node *skiplist_node_new(int level, unsigned long score,
                                        void *data);
void skiplist_node_free(struct skiplist_node *node);
struct skiplist *skiplist_new(skiplist_cmp_t cmp);
void skiplist_free(struct skiplist *skiplist);
void skiplist_clear(struct skiplist *skiplist);
size_t skiplist_len(struct skiplist *skiplist); /* O(1) */
int skiplist_level(struct skiplist *skiplist);  /* O(1) */
int skiplist_push(struct skiplist *skiplist, unsigned long score,
                  void *data); /* O(logN) */
void *skiplist_get(struct skiplist *skiplist,
                   unsigned long score); /* O(logN) */
void *skiplist_pop(struct skiplist *skiplist,
                   unsigned long score);                         /* O(logN) */
void *skiplist_popfirst(struct skiplist *skiplist);              /* O(1) */
void *skiplist_poplast(struct skiplist *skiplist);               /* O(logN) */
struct skiplist_node *skiplist_first(struct skiplist *skiplist); /* O(1) */
struct skiplist_node *skiplist_last(struct skiplist *skiplist);  /* O(1) */
struct skiplist_iter *skiplist_iter_new(struct skiplist *skiplist);
void skiplist_iter_free(struct skiplist_iter *iter);
struct skiplist_node *skiplist_iter_next(struct skiplist_iter *iter); /* O(1) */
struct skiplist_node *skiplist_iter_prev(struct skiplist_iter *iter); /* O(1) */
void skiplist_iter_rewind(struct skiplist_iter *iter);                /* O(1) */
void skiplist_print(struct skiplist *skiplist);

#if defined(__cplusplus)
}
#endif

#endif


text:
FROM ubuntu:16.04
RUN apt-get update && apt-get install -y wget bzip2 git
WORKDIR /root
RUN wget https://repo.continuum.io/miniconda/Miniconda3-latest-Linux-x86_64.sh
RUN echo -e "\nyes\n" | bash Miniconda3-latest-Linux-x86_64.sh
ENV PATH=/root/miniconda3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin
RUN conda update -n base conda
RUN conda config --add channels defaults
RUN conda config --add channels conda-forge
RUN conda config --add channels bioconda
RUN conda install repeatmasker==4.0.6
RUN git clone -b 'v1.0.4-beta' --single-branch --depth 1 https://github.com/vetscience/Tools
RUN cp Tools/Cwl/combinecats/combine.sh .
RUN chmod uog+x combine.sh /root
ENTRYPOINT ["/root/combine.sh"]


text:
<?xml version="1.0" encoding="utf-8"?>
<!--
   Copyright 2015 Synced Synapse. All rights reserved.

   Licensed under the Apache License, Version 2.0 (the "License");
   you may not use this file except in compliance with the License.
   You may obtain a copy of the License at

      http://www.apache.org/licenses/LICENSE-2.0

   Unless required by applicable law or agreed to in writing, software
   distributed under the License is distributed on an "AS IS" BASIS,
   WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
   See the License for the specific language governing permissions and
   limitations under the License.
-->
<resources>
    <dimen name="wizard_title">216dp</dimen>

    <dimen name="control_pad_size">378dp</dimen>
    <dimen name="remote_margin_bottom">16dp</dimen>

    <dimen name="remote_poster_width">110dp</dimen>
    <dimen name="remote_poster_height">162dp</dimen>

    <dimen name="info_poster_width">110dp</dimen>
    <dimen name="info_poster_height">162dp</dimen>
    <dimen name="info_art_height">324dp</dimen>

    <!-- This should be = info_poster_height_square (info_poster_width) + default_paddig -->
    <dimen name="info_poster_bottom_guideline">118dp</dimen>

    <dimen name="default_grid_column_width">250dp</dimen>

    <dimen name="playlist_art_width">88dp</dimen>
    <dimen name="playlist_art_heigth">88dp</dimen>

    <dimen name="movielist_art_width">86dp</dimen>
    <dimen name="movielist_art_heigth">124dp</dimen>

    <dimen name="tvshowlist_art_width">86dp</dimen>
    <dimen name="tvshowlist_art_heigth">124dp</dimen>

    <dimen name="seasonlist_art_width">86dp</dimen>
    <dimen name="seasonlist_art_heigth">124dp</dimen>

    <dimen name="episodelist_art_width">112dp</dimen>
    <dimen name="episodelist_art_heigth">100dp</dimen>

    <dimen name="artistlist_art_width">88dp</dimen>
    <dimen name="artistlist_art_heigth">88dp</dimen>

    <dimen name="albumlist_art_width">88dp</dimen>
    <dimen name="albumlist_art_heigth">88dp</dimen>

    <dimen name="audiogenrelist_art_width">88dp</dimen>
    <dimen name="audiogenrelist_art_heigth">88dp</dimen>

    <dimen name="musicvideolist_art_width">88dp</dimen>
    <dimen name="musicvideolist_art_heigth">88dp</dimen>

    <dimen name="addonlist_art_width">88dp</dimen>
    <dimen name="addonlist_art_heigth">88dp</dimen>

    <dimen name="channellist_art_width">88dp</dimen>
    <dimen name="channellist_art_heigth">88dp</dimen>

    <dimen name="recordinglist_art_width">88dp</dimen>
    <dimen name="recordinglist_art_heigth">88dp</dimen>

</resources>


text:
package com.msun.springStarter.samples;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
import org.springframework.boot.context.embedded.*;
import org.springframework.boot.context.embedded.netty.NettyEmbeddedServletContainerFactory;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.HttpStatus;

/**
 * @author zxc Aug 28, 2015 11:46:11 AM
 */
@Configuration
@ComponentScan
@EnableAutoConfiguration
// @SpringBootApplication
public class TestApplication {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(TestApplication.class, args);
    }

    @Bean
    public EmbeddedServletContainerCustomizer containerCustomizer() {

        return new EmbeddedServletContainerCustomizer() {

            @Override
            public void customize(ConfigurableEmbeddedServletContainer container) {
                container.addErrorPages(new ErrorPage(HttpStatus.UNAUTHORIZED, "/401.html"),
                                        new ErrorPage(HttpStatus.NOT_FOUND, "/404.html"),
                                        new ErrorPage(HttpStatus.INTERNAL_SERVER_ERROR, "/500.html"));
            }
        };
    }

    // 使用内置netty驱动
    @Bean
    public EmbeddedServletContainerFactory servletContainer() {
        return new NettyEmbeddedServletContainerFactory();
    }
}


text:
using System;
using IDI.Core.Authentication;
using IDI.Core.Infrastructure.Queries;
using Newtonsoft.Json;

namespace IDI.Central.Models.Administration
{
    public class RoleModel : IModel, IRole
    {
        [JsonProperty("id")]
        public Guid Id { get; set; }

        [JsonProperty("name")]
        public string Name { get; set; } = "";

        [JsonProperty("descrition")]
        public string Descrition { get; set; } = "";

        [JsonProperty("active")]
        public bool IsActive { get; set; }

        [JsonProperty("permissions")]
        public string Permissions { get; set; }
    }
}


text:
namespace SkiBrain.DataAccess
{
    using System;
    using System.Collections.Generic;

    public partial class Tenant
    {
        public Tenant()
        {
            this.Racers = new HashSet<Racer>();
            this.Parents = new HashSet<Parent>();
            this.MembershipTypes = new HashSet<MembershipType>();
            this.VolunteerRecords = new HashSet<VolunteerRecord>();
            this.VolunteerStatus = new HashSet<VolunteerStatus>();
        }

        public int Id { get; set; }
        public string Name { get; set; }

        public virtual ICollection<Racer> Racers { get; set; }
        public virtual ICollection<Parent> Parents { get; set; }
        public virtual ICollection<MembershipType> MembershipTypes { get; set; }
        public virtual ICollection<VolunteerRecord> VolunteerRecords { get; set; }
        public virtual ICollection<VolunteerStatus> VolunteerStatus { get; set; }
    }
}


text:
<?php

namespace Behat\Testwork\ServiceContainer\Configuration;

use Behat\Testwork\ServiceContainer\Exception\ConfigurationLoadingException;
use Symfony\Component\Yaml\Yaml;

/**
 * Loads configuration from different sources.
 *
 * @author Konstantin Kudryashov <ever.zet@gmail.com>
 */
final class ConfigurationLoader
{
    /**
     * @var null|string
     */
    private $configurationPath;
    /**
     * @var null|string
     */
    private $environmentVariable;
    /**
     * @var Boolean
     */
    private $profileFound;

    /**
     * Constructs reader.
     *
     * @param string $environmentVariableName Environment variable name
     * @param string $configurationPath       Configuration file path
     */
    public function __construct($environmentVariableName = null, $configurationPath = null)
    {
        $this->environmentVariable = $environmentVariableName;
        $this->configurationPath = $configurationPath;
    }

    /**
     * Sets environment variable name.
     *
     * @param null|string $variable
     */
    public function setEnvironmentVariableName($variable)
    {
        $this->environmentVariable = $variable;
    }

    /**
     * Returns environment variable name.
     *
     * @return null|string
     */
    public function getEnvironmentVariableName()
    {
        return $this->environmentVariable;
    }

    /**
     * Sets configuration file path.
     *
     * @param null|string $path
     */
    public function setConfigurationFilePath($path)
    {
        $this->configurationPath = $path;
    }

    /**
     * Returns configuration file path.
     *
     * @return null|string
     */
    public function getConfigurationFilePath()
    {
        return $this->configurationPath;
    }

    /**
     * Reads configuration sequence for specific profile.
     *
     * @param string $profile Profile name
     *
     * @return array
     *
     * @throws ConfigurationLoadingException
     */
    public function loadConfiguration($profile = 'default')
    {
        $configs = array();
        $this->profileFound = false;

        // first is ENV config
        foreach ($this->loadEnvironmentConfiguration() as $config) {
            $configs[] = $config;
        }

        // second is file configuration (if there is some)
        if ($this->configurationPath) {
            foreach ($this->loadFileConfiguration($this->configurationPath, $profile) as $config) {
                $configs[] = $config;
            }
        }

        // if specific profile has not been found
        if ('default' !== $profile && !$this->profileFound) {
            throw new ConfigurationLoadingException(sprintf(
                'Can not find configuration for `%s` profile.',
                $profile
            ));
        }

        return $configs;
    }

    /**
     * Loads information from environment variable.
     *
     * @return array
     *
     * @throws ConfigurationLoadingException If environment variable environment var is set to invalid JSON
     */
    protected function loadEnvironmentConfiguration()
    {
        $configs = array();

        if (!$this->environmentVariable) {
            return $configs;
        }

        if ($envConfig = getenv($this->environmentVariable)) {
            $config = @json_decode($envConfig, true);

            if (!$config) {
                throw new ConfigurationLoadingException(sprintf(
                    'Environment variable `%s` should contain a valid JSON, but it is set to `%s`.',
                    $this->environmentVariable,
                    $envConfig
                ));
            }

            $configs[] = $config;
        }

        return $configs;
    }

    /**
     * Loads information from YAML configuration file.
     *
     * @param string $configPath Config file path
     * @param string $profile    Profile name
     *
     * @return array
     *
     * @throws ConfigurationLoadingException If config file is not found
     */
    protected function loadFileConfiguration($configPath, $profile)
    {
        if (!is_file($configPath) || !is_readable($configPath)) {
            throw new ConfigurationLoadingException(sprintf('Configuration file `%s` not found.', $configPath));
        }

        $basePath = rtrim(dirname($configPath), DIRECTORY_SEPARATOR);
        $config = (array) Yaml::parse($configPath);

        return $this->loadConfigs($basePath, $config, $profile);
    }

    /**
     * Loads configs for provided config and profile.
     *
     * @param string $basePath
     * @param array  $config
     * @param string $profile
     *
     * @return array
     */
    private function loadConfigs($basePath, array $config, $profile)
    {
        $configs = array();

        // first load default profile from current config, but only if custom profile requested
        if ('default' !== $profile && isset($config['default'])) {
            $configs[] = $config['default'];
        }

        // then recursively load profiles from imports
        if (isset($config['imports']) && is_array($config['imports'])) {
            $configs = array_merge($configs, $this->loadImports($basePath, $config['imports'], $profile));
        }

        // then load specific profile from current config
        if (isset($config[$profile])) {
            $configs[] = $config[$profile];
            $this->profileFound = true;
        }

        return $configs;
    }

    /**
     * Loads all provided imports.
     *
     * @param string $basePath
     * @param array  $paths
     * @param string $profile
     *
     * @return array
     */
    private function loadImports($basePath, array $paths, $profile)
    {
        $configs = array();
        foreach ($paths as $path) {
            foreach ($this->parseImport($basePath, $path, $profile) as $importConfig) {
                $configs[] = $importConfig;
            }
        }

        return $configs;
    }

    /**
     * Parses import.
     *
     * @param string $basePath
     * @param string $path
     * @param string $profile
     *
     * @return array
     *
     * @throws ConfigurationLoadingException If import file not found
     */
    private function parseImport($basePath, $path, $profile)
    {
        if (!file_exists($path) && file_exists($basePath . DIRECTORY_SEPARATOR . $path)) {
            $path = $basePath . DIRECTORY_SEPARATOR . $path;
        }

        if (!file_exists($path)) {
            throw new ConfigurationLoadingException(sprintf(
                'Can not import `%s` configuration file. File not found.',
                $path
            ));
        }

        return $this->loadFileConfiguration($path, $profile);
    }
}


text:
<?php
use PayPal\Service\AdaptivePaymentsService;
use PayPal\Types\AP\GetUserLimitsRequest;
use PayPal\Types\Common\AccountIdentifier;
use PayPal\Types\Common\PhoneNumberType;
use PayPal\Types\Common\RequestEnvelope;
require_once('PPBootStrap.php');

// create request
$requestEnvelope = new RequestEnvelope("en_US");
$getUserLimitsReq = new GetUserLimitsRequest($requestEnvelope);
$getUserLimitsReq->country = $_POST['country'];
$getUserLimitsReq->currencyCode = $_POST['currencyCode'];
if( $_POST['email'] != "" || ($_POST['phoneCountry'] != "" && $_POST['phoneNumber'] != "")) {
	$getUserLimitsReq->user = new AccountIdentifier();
	if($_POST['email'] != "") {
		$getUserLimitsReq->user->email =  $_POST['email'];
	}
	if($_POST['phoneCountry'] != "" && $_POST['phoneNumber'] != "") {
		$getUserLimitsReq->user->phone = new PhoneNumberType($_POST['phoneCountry'], $_POST['phoneNumber']);
		if($_POST['phoneExtension'] != "") {
			$getUserLimitsReq->user->phone->extension = $_POST['phoneExtension'];
		}
	}
}
/*
Configuration::getAcctAndConfig() returns array that contains credential and config parameters
 */
$service = new AdaptivePaymentsService(Configuration::getAcctAndConfig());
try {
	$response = $service->GetUserLimits($getUserLimitsReq);
} catch(Exception $ex) {
	require_once 'Common/Error.php';
	exit;
}
?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<title>PayPal Adaptive Payments - Get User Limits</title>
<link href="Common/sdk.css" rel="stylesheet" type="text/css" />

Get User Limits

<?php
$ack = strtoupper($response->responseEnvelope->ack);
if($ack != "SUCCESS"){
	echo "Error ";
	echo "
";
	print_r($response);
	echo "
";
} else {
	echo "
";
	print_r($response);
	echo "
";
}
require_once 'Common/Response.php';
?>


text:
class PrefService;

#if BUILDFLAG(IS_ANDROID)
namespace crash_reporter {
class ChildExitObserver;
}  // namespace crash_reporter
#endif  // BUILDFLAG(IS_ANDROID)

#if defined(USE_AURA)
namespace views {
class ViewsDelegate;
}  // namespace views
#endif  // defined(USE_AURA)

namespace chromecast {
class CastFeatureUpdateObserver;
class CastWebService;
class DisplaySettingsManager;
class ServiceConnector;
class ServiceManagerContext;

#if defined(USE_AURA)
class CastWindowManagerAura;
class CastScreen;
namespace shell {
class CastUIDevTools;
}  // namespace shell
#else
class CastWindowManager;
#endif  // #if defined(USE_AURA)

namespace external_mojo {
class BrokerService;
}  // namespace external_mojo

namespace external_service_support {
class ExternalConnector;
class ExternalService;
}  // namespace external_service_support

namespace media {
class MediaCapsImpl;
class MediaPipelineBackendManager;
class VideoPlaneController;
}  // namespace media

namespace metrics {
class MetricsHelperImpl;
}  // namespace metrics

namespace shell {
class CastBrowserProcess;
class CastContentBrowserClient;

class CastBrowserMainParts : public content::BrowserMainParts {
 public:
  // Creates an implementation of CastBrowserMainParts. Platform should
  // link in an implementation as needed.
  static std::unique_ptr<CastBrowserMainParts> Create(
      CastContentBrowserClient* cast_content_browser_client);

  // This class does not take ownership of |url_request_content_factory|.
  explicit CastBrowserMainParts(
      CastContentBrowserClient* cast_content_browser_client);

  CastBrowserMainParts(const CastBrowserMainParts&) = delete;
  CastBrowserMainParts& operator=(const CastBrowserMainParts&) = delete;

  ~CastBrowserMainParts() override;

  media::MediaPipelineBackendManager* media_pipeline_backend_manager();
  media::MediaCapsImpl* media_caps();
  metrics::MetricsHelperImpl* metrics_helper();
  content::BrowserContext* browser_context();
  external_mojo::BrokerService* broker_service();
  external_service_support::ExternalConnector* connector();
  external_service_support::ExternalConnector* media_connector();
  CastWebService* web_service();

  // content::BrowserMainParts implementation:
  void PreCreateMainMessageLoop() override;
  void PostCreateMainMessageLoop() override;
  void ToolkitInitialized() override;
  int PreCreateThreads() override;
  void PostCreateThreads() override;
  int PreMainMessageLoopRun() override;
  void WillRunMainMessageLoop(
      std::unique_ptr<base::RunLoop>& run_loop) override;
  void PostMainMessageLoopRun() override;
  void PostDestroyThreads() override;

 private:
  std::unique_ptr<CastBrowserProcess> cast_browser_process_;
  // Caches a pointer of the CastContentBrowserClient.
  CastContentBrowserClient* const cast_content_browser_client_ = nullptr;
  std::unique_ptr<ServiceManagerContext> service_manager_context_;
  std::unique_ptr<media::VideoPlaneController> video_plane_controller_;
  std::unique_ptr<media::MediaCapsImpl> media_caps_;
  std::unique_ptr<metrics::MetricsHelperImpl> metrics_helper_;
  std::unique_ptr<ServiceConnector> service_connector_;

  // Created in CastBrowserMainParts::PostCreateThreads():
  std::unique_ptr<external_mojo::BrokerService> broker_service_;
  std::unique_ptr<external_service_support::ExternalService> browser_service_;
  // ExternalConnectors should be destroyed before registered services.
  std::unique_ptr<external_service_support::ExternalConnector> connector_;
  // ExternalConnector for running on the media task runner.
  std::unique_ptr<external_service_support::ExternalConnector> media_connector_;

#if defined(USE_AURA)
  std::unique_ptr<views::ViewsDelegate> views_delegate_;
  std::unique_ptr<CastScreen> cast_screen_;
  std::unique_ptr<CastWindowManagerAura> window_manager_;
  std::unique_ptr<DisplayConfiguratorObserver> display_change_observer_;
#else
  std::unique_ptr<CastWindowManager> window_manager_;
#endif  //  defined(USE_AURA)
  std::unique_ptr<CastWebService> web_service_;
  std::unique_ptr<DisplaySettingsManager> display_settings_manager_;

#if BUILDFLAG(IS_ANDROID)
  void StartPeriodicCrashReportUpload();
  void OnStartPeriodicCrashReportUpload();
  void UploadCrashReport(bool opt_in_stats);
  scoped_refptr<base::SequencedTaskRunner> crash_reporter_runner_;
  std::unique_ptr<base::RepeatingTimer> crash_reporter_timer_;
  std::unique_ptr<crash_reporter::ChildExitObserver> child_exit_observer_;
#endif

  // Tracks all media pipeline backends.
  std::unique_ptr<media::MediaPipelineBackendManager>
      media_pipeline_backend_manager_;

  std::unique_ptr<CastFeatureUpdateObserver> feature_update_observer_;

#if defined(USE_AURA) && !BUILDFLAG(IS_FUCHSIA)
  // Only used when running with --enable-ui-devtools.
  std::unique_ptr<CastUIDevTools> ui_devtools_;
#endif  // defined(USE_AURA) && !BUILDFLAG(IS_FUCHSIA)

  base::WeakPtrFactory<CastBrowserMainParts> weak_factory_{this};
};

}  // namespace shell
}  // namespace chromecast

#endif  // CHROMECAST_BROWSER_CAST_BROWSER_MAIN_PARTS_H_