text:
using System;
using System.Linq;
using System.Collections;
using System.Collections.Generic;
using System.Runtime.CompilerServices;
using System.Text;
using System.Threading;

namespace LanguageExt
{
    internal class SeqLazy<A> : ISeqInternal<A>
    {
        const int DefaultCapacity = 8;
        const int NoCons = 1;

        /// <summary>
        /// Backing data
        /// </summary>
        readonly A[] data;

        /// <summary>
        /// Index into data where the Head is
        /// </summary>
        readonly int start;

        /// <summary>
        /// Known size of the sequence - 0 means unknown
        /// </summary>
        readonly int count;

        /// <summary>
        /// 1 if no more consing is allowed
        /// </summary>
        int consDisallowed;

        /// <summary>
        /// Lazy sequence
        /// </summary>
        readonly Enum<A> seq;

        /// <summary>
        /// Start position in sequence
        /// </summary>
        readonly int seqStart;

        /// <summary>
        /// Constructor
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal SeqLazy(IEnumerable<A> ma) : this(new A[DefaultCapacity], DefaultCapacity, 0, 0, new Enum<A>(ma), 0)
        { }

        /// <summary>
        /// Constructor
        /// </summary>
        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        internal SeqLazy(A[] data, int start, int count, int noCons, Enum<A> seq, int seqStart)
        {
            this.data = data;
            this.start = start;
            this.count = count;
            this.seq = seq;
            this.seqStart = seqStart;
            this.consDisallowed = noCons;
        }

        public A this[int index]
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get
            {
                if (index < 0) throw new IndexOutOfRangeException();
                if (index < count) return data[data.Length - count];
                var lazyIndex = index - count + seqStart;
                var (succ, val) = StreamTo(lazyIndex);
                return succ
                    ? val
                    : throw new IndexOutOfRangeException();
            }
        }

        [MethodImpl(MethodImplOptions.AggressiveInlining)]
        (bool Success, A Value) StreamTo(int index)
        {
            if(index < seq.Count) return seq.Get(index);
            while (seq.Count <= index && seq.Get(seq.Count).Success) ;
            return index < seq.Count
                ? (true, seq.Data[index])
                : (false, default);
        }

        public A Head
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get
            {
                if(count > 0)
                {
                    return data[data.Length - count];
                }
                else if(seq.Count > seqStart)
                {
                    return seq.Data[seqStart];
                }
                else
                {
                    var (succ, val) = seq.Get(seqStart);
                    return succ
                        ? val
                        : throw new InvalidOperationException("Sequence is empty");
                }
            }
        }

        public ISeqInternal<A> Tail
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get
            {
                if(count > 0)
                {
                    return new SeqLazy<A>(data, start + 1, count - 1, NoCons, seq, seqStart);
                }
                else if(seq.Count > seqStart)
                {
                    return new SeqLazy<A>(data, start, count, NoCons, seq, seqStart + 1);
                }
                else
                {
                    var (succ, _) = StreamTo(seq.Count);
                    if(succ)
                    {
                        return new SeqLazy<A>(data, start, count, NoCons, seq, seqStart + 1);
                    }
                    else
                    {
                        return SeqEmptyInternal<A>.Default;
                    }
                }
            }
        }

        public bool IsEmpty
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get => !(count > 0 || (seq.Count - seqStart) > 0 || seq.Get(seqStart).Success);
        }

        public A Last
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get
            {
                InternalStrict();
                return seq.Count > seqStart ? seq.Data[seq.Count - 1]
                     : count > 0            ? data[data.Length - 1]
                     : throw new InvalidOperationException("Sequence is empty");
            }
        }

        public ISeqInternal<A> Init
        {
            get
            {
                var take = Count - 1;
                return take <= 0
                    ? SeqEmptyInternal<A>.Default
                    : Take(take);
            }
        }

        public int Count
        {
            [MethodImpl(MethodImplOptions.AggressiveInlining)]
            get
            {
                InternalStrict();
                return count + seq.Count - seqStart;
            }
        }

        public ISeqInternal<A> Add(A value)
        {
            InternalStrict();
            var seqCount = seq.Count - seqStart;
            var total = count + seqCount + 1;
            var len = DefaultCapacity;
            while (len < total) len = len << 1;

            var ndata = new A[len];

            if (count > 0)
            {
                Array.Copy(data, data.Length - count, ndata, 0, count);
            }
            if (seqCount > 0)
            {
                Array.Copy(seq.Data, seqStart, ndata, count, seqCount);
            }
            ndata[count + seqCount] = value;

            return new SeqStrict<A>(ndata, 0, total, 0, 0);
        }

        public ISeqInternal<A> Cons(A value)
        {
            if (1 == Interlocked.Exchange(ref consDisallowed, 1) || start == 0)
            {
                return CloneCons(value);
            }
            else
            {
                var nstart = start - 1;
                data[nstart] = value;
                return new SeqLazy<A>(data, start - 1, count + 1, 0, seq, seqStart);
            }
        }

        SeqLazy<A> CloneCons(A value)
        {
            if (start == 0)
            {
                // Find the new size of the data array
                var nlength = Math.Max(data.Length << 1, 1);

                // Allocate it
                var ndata = new A[nlength];

                // Copy the old data block to the second half of the new one
                // so we have space on the left-hand-side to put the cons'd
                // value
                System.Array.Copy(data, 0, ndata, data.Length, data.Length);

                // The new head position will be 1 cell to to left of the
                // middle of the newly allocated block.
                var nstart = data.Length - 1;

                // We have one more item
                var ncount = count + 1;

                // Set the value in the new data block
                ndata[nstart] = value;

                // Return everything
                return new SeqLazy<A>(ndata, nstart, ncount, 0, seq, seqStart);
            }
            else
            {
                // We're cloning because there are multiple cons operations
                // from the same Seq.  We can't keep walking along the same
                // array, so we clone with the exact same settings and insert

                var ndata = new A[data.Length];
                var nstart = start - 1;

                System.Array.Copy(data, start, ndata, start, count);

                ndata[nstart] = value;

                return new SeqLazy<A>(ndata, nstart, count + 1, 0, seq, seqStart);
            }
        }

        public S Fold<S>(S state, Func<S, A, S> f)
        {
            InternalStrict();
            if (count > 0)
            {
                for (var i = data.Length - count; i < data.Length; i++)
                {
                    state = f(state, data[i]);
                }
            }
            if (seq.Count - seqStart > 0)
            {
                var scount = seq.Count;
                var sdata = seq.Data;
                for (var i = seqStart; i < scount; i++)
                {
                    state = f(state, sdata[i]);
                }
            }
            return state;
        }

        public S FoldBack<S>(S state, Func<S, A, S> f)
        {
            InternalStrict();
            if (seq.Count - seqStart > 0)
            {
                var sdata = seq.Data;
                for (var i = seq.Count - 1; i >= seqStart; i--)
                {
                    state = f(state, sdata[i]);
                }
            }
            if (count > 0)
            {
                var nstart = data.Length - count;
                for (var i = data.Length - 1; i >= nstart; i--)
                {
                    state = f(state, data[i]);
                }
            }
            return state;
        }

        public ISeqInternal<A> Skip(int amount)
        {
            if(amount < count)
            {
                return new SeqLazy<A>(data, start + amount, count - amount, NoCons, seq, seqStart);
            }
            else if (amount == count)
            {
                return new SeqLazy<A>(new A[DefaultCapacity], DefaultCapacity, 0, 0, seq, seqStart);
            }
            else
            {
                var namount = amount - count;
                var end = seqStart + namount;
                if (end > seq.Count)
                {
                    for (var i = seqStart; i < end && seq.Get(i).Success; i++) ;
                }

                if(seq.Count >= end)
                {
                    return new SeqLazy<A>(new A[DefaultCapacity], DefaultCapacity, 0, 0, seq, end);
                }
                else
                {
                    return SeqEmptyInternal<A>.Default;
                }
            }
        }

        ISeqInternal<A> InternalStrict()
        {
            while (seq.Get(seq.Count).Success) ;
            return this;
        }

        public ISeqInternal<A> Strict()
        {
            InternalStrict();

            var len = DefaultCapacity;
            var ncount = count + seq.Count - seqStart;
            while (len < ncount) len = len << 1;

            var nstart = (len - ncount) >> 1;

            var ndata = new A[len];
            if (count > 0)
            {
                Array.Copy(data, data.Length - count, ndata, nstart, count);
            }
            if (seq.Count > 0)
            {
                Array.Copy(seq.Data, seqStart, ndata, nstart + count, seq.Count - seqStart);
            }
            return new SeqStrict<A>(ndata, nstart, ncount, 0, 0);
        }

        public ISeqInternal<A> Take(int amount)
        {
            if(amount <= count)
            {
                var ndata = new A[data.Length];
                var nstart = data.Length - count;
                Array.Copy(data, nstart, ndata, nstart, data.Length);
                return new SeqStrict<A>(ndata, start, amount, 0, 0);
            }
            else
            {
                var namount = amount - count;
                var end = seqStart + namount;
                for (var i = seqStart; i < end && seq.Get(i).Success; i++) ;
                var seqLen = seq.Count - seqStart;

                var len = DefaultCapacity;
                while (len < amount) len = len << 1;

                var ndata = new A[len];
                var nstart = (len - amount) >> 1;
                if (count > 0)
                {
                    Array.Copy(data, data.Length - count, ndata, nstart, count);
                }
                if (seq.Count - seqStart > 0)
                {
                    Array.Copy(seq.Data, seqStart, ndata, nstart + count, amount - count);
                }
                return new SeqStrict<A>(ndata, nstart, amount, 0, 0);
            }
        }

        public IEnumerator<A> GetEnumerator()
        {
            int nstart = data.Length - count;
            int nend = data.Length;

            for (var i = nstart; i < nend; i++)
            {
                yield return data[i];
            }
            for(var i = seqStart; ; i++)
            {
                var (succ, val) = seq.Get(i);
                if(succ)
                {
                    yield return val;
                }
                else
                {
                    yield break;
                }
            }
        }

        IEnumerator IEnumerable.GetEnumerator()
        {
            int nstart = data.Length - count;
            int nend = data.Length;

            for (var i = nstart; i < nend; i++)
            {
                yield return data[i];
            }
            for (var i = seqStart; ; i++)
            {
                var (succ, val) = seq.Get(i);
                if (succ)
                {
                    yield return val;
                }
                else
                {
                    yield break;
                }
            }
        }

        public ISeqInternal<A> Filter(Func<A, bool> f) =>
            new SeqLazy<A>(this.Where(f));

        public ISeqInternal<B> Map<B>(Func<A, B> f) =>
            new SeqLazy<B>(this.Select(f));

        public Unit Iter(Action<A> f)
        {
            foreach(var item in this)
            {
                f(item);
            }
            return default;
        }

        public bool Exists(Func<A, bool> f)
        {
            foreach(var item in this)
            {
                if (f(item))
                {
                    return true;
                }
            }
            return false;
        }

        public bool ForAll(Func<A, bool> f)
        {
            foreach (var item in this)
            {
                if (!f(item))
                {
                    return false;
                }
            }
            return true;
        }

        public SeqType Type => SeqType.Lazy;
    }
}


text:
/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
/*
 *     Copyright 2012 Couchbase, Inc
 *
 *   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.
 */

#ifndef SRC_ACCESS_SCANNER_H_
#define SRC_ACCESS_SCANNER_H_ 1

#include "config.h"

#include <string>

#include "common.h"
#include "dispatcher.h"
#include "ep_engine.h"

// Forward declaration.
class EventuallyPersistentStore;
class AccessScannerValueChangeListener;

class AccessScanner : public DispatcherCallback {
    friend class AccessScannerValueChangeListener;
public:
    AccessScanner(EventuallyPersistentStore &_store, EPStats &st,
                  size_t sleetime);
    bool callback(Dispatcher &d, TaskId &t);
    std::string description();
    size_t startTime();

private:
    EventuallyPersistentStore &store;
    EPStats &stats;
    size_t sleepTime;
    bool available;
};

#endif  // SRC_ACCESS_SCANNER_H_

redpajama_set_name: RedPajamaGithub


text:
package org.apache.fluo.accumulo.iterators;

import java.io.IOException;
import java.util.Collection;
import java.util.Collections;
import java.util.Map;
import java.util.Set;

import com.google.common.annotations.VisibleForTesting;
import com.google.common.base.Preconditions;
import org.apache.accumulo.core.client.IteratorSetting;
import org.apache.accumulo.core.data.ArrayByteSequence;
import org.apache.accumulo.core.data.ByteSequence;
import org.apache.accumulo.core.data.Key;
import org.apache.accumulo.core.data.PartialKey;
import org.apache.accumulo.core.data.Range;
import org.apache.accumulo.core.data.Value;
import org.apache.accumulo.core.iterators.IteratorEnvironment;
import org.apache.accumulo.core.iterators.SortedKeyValueIterator;
import org.apache.fluo.accumulo.util.ColumnConstants;
import org.apache.fluo.accumulo.values.WriteValue;

public class SnapshotIterator implements SortedKeyValueIterator<Key, Value> {

  @VisibleForTesting
  static final String TIMESTAMP_OPT = "timestampOpt";

  static final String RETURN_READLOCK_PRESENT_OPT = "rrlpOpt";

  private static final ByteSequence NOTIFY_CF_BS =
      new ArrayByteSequence(ColumnConstants.NOTIFY_CF.toArray());

  static final Set<ByteSequence> NOTIFY_CF_SET = Collections.singleton(NOTIFY_CF_BS);

  private TimestampSkippingIterator source;
  private long snaptime;
  private boolean hasTop = false;

  private boolean returnReadLockPresent = false;

  private final Key curCol = new Key();

  private Key readLockIgnore;
  private Key readLockKey;
  private Value readLockValue;

  private void rememberReadLock(Key key, Value val) {
    Preconditions.checkState(readLockKey == null && readLockValue == null);
    if (readLockIgnore == null
        || !key.equals(readLockIgnore, PartialKey.ROW_COLFAM_COLQUAL_COLVIS)) {
      readLockKey = new Key(key);
      readLockValue = new Value(val);
    }
  }

  private void ignoreReadLock(Key key) {
    readLockIgnore = key;
  }

  private void clearReadLock() {
    readLockKey = null;
    readLockValue = null;
    readLockIgnore = null;
  }

  private void findTop() throws IOException {
    outer: while (source.hasTop() && readLockKey == null) {
      long invalidationTime = -1;
      long dataPointer = -1;

      if (source.getTopKey().getColumnFamilyData().equals(NOTIFY_CF_BS)) {
        throw new IllegalStateException("seeing notifications during snapshot iteration");
      }

      curCol.set(source.getTopKey());

      while (source.hasTop()
          && curCol.equals(source.getTopKey(), PartialKey.ROW_COLFAM_COLQUAL_COLVIS)) {
        long colType = source.getTopKey().getTimestamp() & ColumnConstants.PREFIX_MASK;
        long ts = source.getTopKey().getTimestamp() & ColumnConstants.TIMESTAMP_MASK;

        if (colType == ColumnConstants.TX_DONE_PREFIX) {
          source.skipToPrefix(curCol, ColumnConstants.WRITE_PREFIX);
          continue;
        } else if (colType == ColumnConstants.WRITE_PREFIX) {
          long timePtr = WriteValue.getTimestamp(source.getTopValue().get());

          if (timePtr > invalidationTime) {
            invalidationTime = timePtr;
          }

          if (dataPointer == -1) {
            if (ts <= snaptime) {
              dataPointer = timePtr;
              source.skipToPrefix(curCol, ColumnConstants.DEL_LOCK_PREFIX);
              continue;
            } else {
              source.skipToTimestamp(curCol, ColumnConstants.WRITE_PREFIX | snaptime);
              continue;
            }
          }
        } else if (colType == ColumnConstants.DEL_LOCK_PREFIX) {
          if (ts > invalidationTime) {
            invalidationTime = ts;
          }
          if (returnReadLockPresent) {
            source.skipToPrefix(curCol, ColumnConstants.RLOCK_PREFIX);
          } else {
            source.skipToPrefix(curCol, ColumnConstants.LOCK_PREFIX);
          }
          continue;

        } else if (colType == ColumnConstants.RLOCK_PREFIX) {
          if (returnReadLockPresent) {
            rememberReadLock(source.getTopKey(), source.getTopValue());
          }

          source.skipToPrefix(curCol, ColumnConstants.LOCK_PREFIX);
          continue;
        } else if (colType == ColumnConstants.LOCK_PREFIX) {
          if (ts > invalidationTime && ts <= snaptime) {
            // nothing supersedes this lock, therefore the column is locked
            return;
          } else {
            if (dataPointer == -1) {
              source.skipColumn(curCol);
              continue outer;
            } else {
              source.skipToTimestamp(curCol, ColumnConstants.DATA_PREFIX | dataPointer);
              continue;
            }
          }
        } else if (colType == ColumnConstants.DATA_PREFIX) {
          if (dataPointer == ts) {
            // found data for this column
            return;
          }

          if (ts < dataPointer || dataPointer == -1) {
            source.skipColumn(curCol);
            continue outer;
          }

          if (ts > dataPointer) {
            source.skipToTimestamp(curCol, ColumnConstants.DATA_PREFIX | dataPointer);
            continue;
          }
        } else if (colType == ColumnConstants.ACK_PREFIX) {
          if (dataPointer == -1) {
            source.skipColumn(curCol);
            continue outer;
          } else {
            source.skipToTimestamp(curCol, ColumnConstants.DATA_PREFIX | dataPointer);
            continue;
          }
        } else {
          throw new IllegalArgumentException();
        }

        // TODO handle case where dataPointer >=0, but no data was found
        source.next();
      }
    }
  }

  @Override
  public void init(SortedKeyValueIterator<Key, Value> source, Map<String, String> options,
      IteratorEnvironment env) throws IOException {
    this.source = new TimestampSkippingIterator(source);
    this.snaptime = Long.parseLong(options.get(TIMESTAMP_OPT));
    this.returnReadLockPresent =
        Boolean.parseBoolean(options.getOrDefault(RETURN_READLOCK_PRESENT_OPT, "false"));
    // TODO could require client to send version as a sanity check
  }

  @Override
  public boolean hasTop() {
    return hasTop && (readLockKey != null || source.hasTop());
  }

  @Override
  public void next() throws IOException {
    if (readLockKey != null) {
      clearReadLock();
    } else {
      curCol.set(source.getTopKey());
      source.skipColumn(curCol);

      findTop();
    }
  }

  @Override
  public void seek(Range range, Collection<ByteSequence> columnFamilies, boolean inclusive)
      throws IOException {

    Range newRange = range;
    Collection<ByteSequence> cols;
    boolean inc;

    clearReadLock();

    // handle continue case
    hasTop = true;
    if (range.getStartKey() != null && range.getStartKey().getTimestamp() != Long.MAX_VALUE
        && !range.isStartKeyInclusive()) {

      if ((range.getStartKey().getTimestamp()
          & ColumnConstants.PREFIX_MASK) == ColumnConstants.RLOCK_PREFIX) {
        Key currCol = new Key(range.getStartKey());
        currCol.setTimestamp(Long.MAX_VALUE);
        newRange = new Range(currCol, true, range.getEndKey(), range.isEndKeyInclusive());
        ignoreReadLock(currCol);
      } else {

        Key nextCol = range.getStartKey().followingKey(PartialKey.ROW_COLFAM_COLQUAL_COLVIS);
        if (range.afterEndKey(nextCol)) {
          hasTop = false;
          return;
        } else {
          newRange = new Range(nextCol, true, range.getEndKey(), range.isEndKeyInclusive());
        }
      }
    } else {
      newRange = range;
    }

    if (columnFamilies.size() == 0 && inclusive == false) {
      cols = NOTIFY_CF_SET;
      inc = false;
    } else {
      cols = columnFamilies;
      inc = inclusive;
    }

    source.seek(newRange, cols, inc);
    findTop();
  }

  @Override
  public Key getTopKey() {
    if (readLockKey != null) {
      return readLockKey;
    } else {
      return source.getTopKey();
    }
  }

  @Override
  public Value getTopValue() {
    if (readLockValue != null) {
      return readLockValue;
    } else {
      return source.getTopValue();
    }
  }

  @Override
  public SortedKeyValueIterator<Key, Value> deepCopy(IteratorEnvironment env) {
    throw new UnsupportedOperationException();
  }

  public static void setSnaptime(IteratorSetting cfg, long time) {
    if (time < 0 || (ColumnConstants.PREFIX_MASK & time) != 0) {
      throw new IllegalArgumentException();
    }
    cfg.addOption(TIMESTAMP_OPT, time + "");
  }

  public static void setReturnReadLockPresent(IteratorSetting cfg, boolean rrlp) {
    cfg.addOption(RETURN_READLOCK_PRESENT_OPT, rrlp + "");
  }
}


text:
package uk.co.optimisticpanda.gtest.dto.util;

import java.util.concurrent.atomic.AtomicInteger;
import java.util.function.Function;
import java.util.function.Supplier;

public class FunctionUtils {

	/**
	 * A value generator instance that is used as a null object, it does not
	 * generate anything and throws an {@link UnsupportedOperationException} if
	 * {@link #generate()} is called.
	 */
	public static final Supplier<?> NOT_COVERED = new Supplier<Object>() {
		@Override
		public Object get() {
			throw new UnsupportedOperationException("This generator does not generate values");
		}
	};

	public static <T> Function<T, IndexedItem<T>> indexed() {
		AtomicInteger count = new AtomicInteger();
		return (t) -> new IndexedItem<T>(count.getAndIncrement(), t);
	}

	public static class IndexedItem<T> {
		public final Integer index;
		public final T item;

		public IndexedItem(Integer index, T item) {
			this.index = index;
			this.item = item;
		}
	}

	public static class Suppliers{
		public static <T> Supplier<T> of(T instance) {
			return () -> instance;
		}

		public static <T> Supplier<T> of(Supplier<T> instance) {
			return () -> instance.get();
		}
	}
}


text:
package com.parse.starter;
import android.app.Service;
import android.content.Intent;
import android.os.Handler;
import android.os.IBinder;

//繼承android.app.Service
public class ReadWriteService extends Service {   // 隨時會收到有人寄好友信或是新的聊天訊息
    private Handler handler = new Handler();

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public void onStart(Intent intent, int startId) {
        handler.postDelayed(showTime, 1000);
        super.onStart(intent, startId);
    }

    @Override
    public void onDestroy() {
        handler.removeCallbacks(showTime);
        super.onDestroy();
    }

    private Runnable showTime = new Runnable() {
        @Override
		public void run() {
            //log目前時間
        	//System.out.println("toString())"+new Date().toString());
            //Log.i("time:", new Date().toString());
            handler.postDelayed(this, 1000);
        }
    };
}


text:
<?php

namespace Magento\Sales\Model\ResourceModel\Order\Creditmemo;

use Magento\Sales\Model\ResourceModel\EntityAbstract as SalesResource;
use Magento\Sales\Model\Spi\CreditmemoItemResourceInterface;

/**
 * Flat sales order creditmemo item resource
 *
 * @author      Magento Core Team <core@magentocommerce.com>
 */
class Item extends SalesResource implements CreditmemoItemResourceInterface
{
    /**
     * Event prefix
     *
     * @var string
     */
    protected $_eventPrefix = 'sales_order_creditmemo_item_resource';

    /**
     * Model initialization
     *
     * @return void
     */
    protected function _construct()
    {
        $this->_init('sales_creditmemo_item', 'entity_id');
    }

    /**
     * @param \Magento\Framework\Model\AbstractModel $object
     * @return $this
     */
    protected function _beforeSave(\Magento\Framework\Model\AbstractModel $object)
    {
        /**@var $object \Magento\Sales\Model\Order\Creditmemo\Item*/
        if (!$object->getParentId() && $object->getCreditmemo()) {
            $object->setParentId($object->getCreditmemo()->getId());
        }
        return parent::_beforeSave($object);
    }
}


text:
    <java-class-file name="D:\Experiments\Analisi di Sopravvivenza\Progetto16715\ProgettiDaAnalizzare\jhotdraw\JHotDraw 7.4.1\JHotDraw 7.4.1\Source\jhotdraw7\src\main\java\org\jhotdraw\gui\plaf\palette\PaletteLazyActionMap.java">
        <package-decl name="org.jhotdraw.gui.plaf.palette"/>
        <class name="PaletteLazyActionMap" visibility="public">
            <method name="installLazyActionMap" visibility="protected" static="true">
            </method>
            <method name="getActionMap" visibility="protected" static="true">
            </method>
            <constructor visibility="private" name="PaletteLazyActionMap">
            </constructor>
            <method name="put" visibility="public">
            </method>
            <method name="put" visibility="public">
            </method>
            <method name="get" visibility="public">
            </method>
            <method name="remove" visibility="public">
            </method>
            <method name="clear" visibility="public">
            </method>
            <method name="keys" visibility="public">
            </method>
            <method name="size" visibility="public">
            </method>
            <method name="allKeys" visibility="public">
            </method>
            <method name="setParent" visibility="public">
            </method>
            <method name="loadIfNecessary" visibility="private">
            </method>
        </class>
    </java-class-file>


text:
import csv
import json
import os
import itertools

histogram={}
#going to need to do something different with the path
with open('C:\Users\Alexander\Documents\GitHub\injustice_dropper\data\\violations.csv', 'rb') as citations:
    reader = csv.DictReader(citations)
    for row in reader:
        key=row['violation_description']
        if key not in histogram:
            histogram[key]={'fine_amount':{'sum':0,'total':0},'court_cost':{'sum':0,'total':0}}
        if len(row['court_cost'])>0:
            cost=float(row['court_cost'].strip('$'))
            histogram[key]['court_cost']['sum']+=cost
            histogram[key]['court_cost']['total']+=1
        if len(row['fine_amount'])>0:
            cost=float(row['fine_amount'].strip('$'))
            histogram[key]['fine_amount']['sum']+=cost
            histogram[key]['fine_amount']['total']+=1
print histogram
output={}
for key in histogram:
    output[key]={
        'fine_amount':float(histogram[key]['fine_amount']['sum'])/float(histogram[key]['fine_amount']['total']),
        'court_cost':float(histogram[key]['court_cost']['sum'])/float(histogram[key]['court_cost']['total']),
    }
print(output)


text:
<resources>
    <attr name="segmentedControlButtonStyle" format="reference" />
    <declare-styleable name="SegmentedControlButton" />
</resources>


text:
namespace arb {

// Stiches represent an alternative building block for morphologies.
//
// A stitch describes a portion of the morphology delimited by two
// `mpoint`s. Stitches can be attached to a parent stich at any
// point along the parent, interpolated linearly from the end points.
// Each stitch is associated with a unique string label, and optionally
// an integer tag value.
//
// The stitch builder collects stitches and produces the corresponding
// morphology and region/location labels.

struct mstitch {
    std::string id;
    std::optional<mpoint> prox;
    mpoint dist;
    int tag;

    mstitch(std::string id, mpoint prox, mpoint dist, int tag = 0):
        id(std::move(id)), prox(std::move(prox)), dist(std::move(dist)), tag(tag)
    {}

    mstitch(std::string id, mpoint dist, int tag = 0):
        id(std::move(id)), dist(std::move(dist)), tag(tag)
    {}
};

struct stitch_builder_impl;
struct stitched_morphology;

struct ARB_ARBOR_API stitch_builder {
    stitch_builder();

    stitch_builder(const stitch_builder&) = delete;
    stitch_builder(stitch_builder&&);

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

    // Make a new stitch in the morphology, return reference to self.
    //
    // If the stitch does not contained a proximal point, it will be
    // inferred from the point where it attaches to the parent stitch.
    // If the parent is omitted, it will be taken to be the last stitch
    // added.

    stitch_builder& add(mstitch f, const std::string& parent_id, double along = 1.);
    stitch_builder& add(mstitch f, double along = 1.);

    ~stitch_builder();
private:
    friend stitched_morphology;
    std::unique_ptr<stitch_builder_impl> impl_;
};

// From stitch builder construct morphology, region expressions.

struct stitched_morphology_impl;

struct ARB_ARBOR_API stitched_morphology {
    stitched_morphology() = delete;
    stitched_morphology(const stitch_builder&); // implicit
    stitched_morphology(stitch_builder&&); // implicit

    stitched_morphology(const stitched_morphology&) = delete;
    stitched_morphology(stitched_morphology&&);

    arb::morphology morphology() const;
    region stitch(const std::string& id) const;
    std::vector<msize_t> segments(const std::string& id) const;

    // Create labeled regions for each stitch with label equal to the stitch id, prepended by `prefix`.
    label_dict labels(const std::string& prefix="") const;

    ~stitched_morphology();
private:
    std::unique_ptr<stitched_morphology_impl> impl_;
};

} // namesapce arb


text:
<html ⚡ i-amphtml-layout>
  <head>
    <style amp-runtime></style>
    <script async src=https://cdn.ampproject.org/v0.js></script>
    <script async custom-element=amp-img src=https://cdn.ampproject.org/v0/amp-img-0.1.js></script>
    <noscript><style amp-boilerplate>body{-webkit-animation:none;-moz-animation:none;-ms-animation:none;animation:none}</style></noscript>
    <style amp-boilerplate>body{-webkit-animation:-amp-start 8s steps(1,end) 0s 1 normal both;
-moz-animation:-amp-start 8s steps(1,end) 0s 1 normal both;-ms-animation:-amp-start 8s steps(1,end) 0s 1 normal both;animation:-amp-start 8s steps(1,end) 0s 1 normal both}@-webkit-keyframes-amp-start{from{visibility:hidden}to{visibility:visible}}@-moz-keyframes-amp-start{from{visibility:hidden}to{visibility:visible}}@-ms-keyframes-amp-start{from{visibility:hidden}to{visibility:visible}}@-o-keyframes-amp-start{from{visibility:hidden}to{visibility:visible}}@keyframes -amp-start{from{visibility:hidden}to{visibility:visible}}</style>
    <link href=https://example.com/favicon.ico rel=icon>
  </head>
  <body>
    <amp-img
      height=300
      layout=responsive
      sizes="(min-width: 320px) 320px, 100vw"
      src=https://acme.org/image1.png
      width=400
      class="i-amphtml-layout-responsive i-amphtml-layout-size-defined"
      i-amphtml-layout=responsive>
      <i-amphtml-sizer
        style=display:block;padding-top:75.0000%;>
      </i-amphtml-sizer>
    </amp-img>
    <amp-img
      height=256
      heights="(min-width:500px) 200px, 80%"
      layout=responsive
      src=https://acme.org/image1.png
      width=320
      class="i-amphtml-layout-responsive i-amphtml-layout-size-defined"
      i-amphtml-layout=responsive>
      <i-amphtml-sizer
        style=display:block;padding-top:80.0000%;>
      </i-amphtml-sizer>
    </amp-img>
    <amp-img
      height=355
      layout=fixed
      media="(min-width: 650px) and handheld"
      src=wide.jpg
      width=466
      class="i-amphtml-layout-fixed i-amphtml-layout-size-defined"
      style=width:466px;height:355px;
      i-amphtml-layout=fixed>
    </amp-img>
  </body>
</html>


text:
namespace rs2
{
    class stream_profile;
}

namespace librealsense
{
    class units_transform : public stream_filter_processing_block
    {
    public:
        units_transform();

    protected:
        void update_configuration(const rs2::frame& f);
        rs2::frame process_frame(const rs2::frame_source& source, const rs2::frame& f) override;
        bool should_process(const rs2::frame& frame) override;

    private:
        rs2::stream_profile     _target_stream_profile;
        rs2::stream_profile     _source_stream_profile;

        optional_value<float>   _depth_units;
        size_t                  _width, _height, _stride;
        size_t                  _bpp;
    };
}


text:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:background="#ccc"
    tools:context="com.example.deneme.BlankFragment">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:theme="@style/Widget.AppCompat.Light.ActionBar"/>

    <android.support.v7.widget.CardView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_margin="16dp"
        app:cardBackgroundColor="#3F51B5"
        app:cardElevation="4dp"
        app:contentPadding="16dp">

        <!-- TODO: Update blank fragment layout -->
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#fff"
            android:text="@string/hello_blank_fragment" />

    </android.support.v7.widget.CardView>

</LinearLayout>


text:
package com.safecharge.request;

import javax.validation.ConstraintViolationException;

import com.safecharge.request.basic.EditUPOBasicRequest;
import com.safecharge.util.Constants;
import com.safecharge.util.ValidChecksum;
import com.safecharge.util.ValidationUtils;

@ValidChecksum(orderMappingName = Constants.ChecksumOrderMapping.SUSPEND_UPO)
public class SuspendUPORequest extends EditUPOBasicRequest {

    public static Builder builder() {
        return new Builder();
    }

    public static class Builder extends EditUPOBasicRequest.Builder<SuspendUPORequest.Builder> {

        @Override
        public SafechargeBaseRequest build() throws ConstraintViolationException {
            SuspendUPORequest suspendUPORequest = new SuspendUPORequest();
            return ValidationUtils.validate(super.build(suspendUPORequest));
        }
    }
}


text:
<?php

namespace app\modules\aux_planejamento\models\solicitacoes;

use Yii;

use app\modules\aux_planejamento\models\base\Colaborador;
use app\modules\aux_planejamento\models\base\Unidade;
use app\modules\aux_planejamento\models\cadastros\Segmento;
use app\modules\aux_planejamento\models\cadastros\Tipo;

/**
 * This is the model class for table "materialcopias_matc".
 *
 * @property integer $matc_id
 * @property string $matc_descricao
 * @property integer $matc_qtoriginais
 * @property integer $matc_qtexemplares
 * @property integer $matc_mono
 * @property integer $matc_color
 * @property string $matc_curso
 * @property string $matc_centrocusto
 * @property string $matc_unidade
 * @property string $matc_solicitante
 * @property string $matc_data
 * @property integer $situacao_id
 * @property integer $matc_qteCopias
 * @property integer $matc_qteTotal
 * @property integer $matc_totalValorMono
 * @property integer $matc_totalValorColor
 * @property string $matc_ResponsavelAut
 * @property string $matc_dataAut
 *
 * @property CopiasacabamentoCopac[] $copiasacabamentoCopacs
 * @property SituacaomatcopiasSitmat $situacao
 */
class MaterialCopiasAprovadas extends \yii\db\ActiveRecord
{
    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return 'materialcopias_matc';
    }

    /**
     * @return \yii\db\Connection the database connection used by this AR class.
     */
    public static function getDb()
    {
        return Yii::$app->get('db_apl');
    }

    /**
     * @inheritdoc
     */
    public function rules()
    {
        return [
            [['matc_segmento', 'matc_tipoacao', 'matc_curso', 'situacao_id', 'matc_totalValorMono', 'matc_totalValorColor'], 'required'],
            [['matc_segmento', 'matc_tipoacao', 'situacao_id', 'matc_autorizado', 'matc_encaminhadoRepro'], 'integer'],
            [['matc_data', 'matc_dataGer', 'matc_dataAut', 'matc_dataRepro'], 'safe'],
            [['matc_totalValorMono', 'matc_totalValorColor'], 'number'],
            [['matc_curso'], 'string', 'max' => 255],
            [['matc_centrocusto', 'matc_unidade', 'matc_solicitante', 'matc_ResponsavelAut', 'matc_ResponsavelRepro'], 'string', 'max' => 100],
            [['situacao_id'], 'exist', 'skipOnError' => true, 'targetClass' => Situacao::className(), 'targetAttribute' => ['situacao_id' => 'sitmat_id']],
        ];
    }

    /**
     * @inheritdoc
     */
    public function attributeLabels()
    {
        return [
            'matc_id' => 'Código',
            'matc_segmento' => 'Segmento',
            'matc_tipoacao' => 'Tipo de Ação',
            'matc_curso' => 'Curso',
            'matc_centrocusto' => 'Centro de Custo',
            'matc_unidade' => 'Unidade',
            'matc_solicitante' => 'Solicitante',
            'matc_data' => 'Data da Solicitação',
            'situacao_id' => 'Situação',
            'matc_totalValorMono' => 'Total em cópias mono',
            'matc_totalValorColor' => 'Total em cópias coloridas',
            'matc_totalGeral' => 'Total Geral',
        ];
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getCopiasacabamentoCopacs()
    {
        return $this->hasMany(CopiasacabamentoCopac::className(), ['materialcopias_id' => 'matc_id']);
    }

    /**
     * @return \yii\db\ActiveQuery
     */
    public function getSituacao()
    {
        return $this->hasOne(Situacao::className(), ['sitmat_id' => 'situacao_id']);
    }

    public function getColaborador()
    {
        return $this->hasOne(Colaborador::className(), ['col_codcolaborador' => 'matc_solicitante']);
    }

    public function getUnidade()
    {
        return $this->hasOne(Unidade::className(), ['uni_codunidade' => 'matc_unidade']);
    }

    public function getSegmento()
    {
        return $this->hasOne(Segmento::className(), ['seg_codsegmento' => 'matc_segmento']);
    }

    public function getTipo()
    {
        return $this->hasOne(Tipo::className(), ['tip_codtipoa' => 'matc_tipoacao']);
    }

}


text: For the one who has Dream


text:
require 'rails_helper'

RSpec.describe UsersController, type: :controller do
  render_views

  context 'when user already signed in' do
    let(:user) { create :user }

    before { sign_in(user) }

    describe 'GET #new' do
      subject { get :new }

      it { is_expected.to redirect_to(tasks_url) }
    end

    describe 'POST #create' do
      subject { post :create }

      it { is_expected.to redirect_to(tasks_url) }
    end
  end

  context 'when user is not signed' do
    describe 'GET #new' do
      subject { get :new }

      it { is_expected.to have_http_status(200) }
    end

    describe 'POST #create' do
      subject { post :create, params: { user: user_attrs } }

      context 'with valid attributes' do
        let(:user_attrs) { attributes_for(:user) }

        it { expect { subject }.to change(User, :count).by(1) }
        it { is_expected.to redirect_to(tasks_url) }

        it 'sign in as created user' do
          subject
          expect(controller.current_user).to eq(User.last)
        end
      end

      context 'with invalid attributes' do
        let(:user_attrs) { { email: '' } }

        it { is_expected.to render_template(:new) }
      end
    end
  end
end


text:
function enableAccessibilityEventsPermission() {
  return new Promise(function(resolve, reject) {
    PermissionsHelper.setPermission(
        'accessibility-events', 'granted').then(function() {
      // Don't resolve the promise until the permission has propagated
      // to AXObjectCacheImpl.
      let timerId;
      function checkPermission() {
        if (accessibilityController.canCallAOMEventListeners) {
          window.clearInterval(timerId);
          resolve();
        }
      }
      timerId = window.setInterval(checkPermission, 0);
    });
  });
}


text:
using Microsoft.VisualStudio.TestTools.UnitTesting;

namespace Automoqer.Test
{
    [TestClass]
    public class AutoMoqerContainerTests
    {
        [TestMethod]
        public void CreateServiceShouldCreateTheInstance()
        {
            // Arrange
            using (var autoMoqer = new AutoMoqer<Foo>()
                .Build())
            {
                // Act
                autoMoqer.CreateService();

                // Assert
                Assert.IsNotNull(autoMoqer.Service);
            }
        }

        private class Foo
        {
            // nothing to do here
        }
    }
}


text:
var swisstopoapi = {};
swisstopoapi.waitforheight = [];
swisstopoapi.timeoutid;

/**
 * @description loads a jsonp file: internal function
 * @param {string} url the request url
 * @param {function} cb the callback function
 */
swisstopoapi.getJSONP = function(url,cb)
{
   var cbnum = "cb"+swisstopoapi.getJSONP.counter++;
   var cbname ="swisstopoapi.getJSONP."+cbnum;

   url+="&cb="+cbname;

   var script = document.createElement("script");
   swisstopoapi.getJSONP[cbnum] = function(response)
                     {
                        try{
                           cb(response)
                        }
                        finally
                        {
                           delete swisstopoapi.getJSONP[cbnum];
                           script.parentNode.removeChild(script);
                        }
                     }
   script.src = url;
   document.body.appendChild(script);
}
swisstopoapi.getJSONP.counter = 0;

/**
 * @description loads a jsonp file
 * @param {string} place the place to look for
 */
swisstopoapi.sendQuery = function(place)
{
   /*clear result list */
   var node = document.getElementById('divSearchResults');
   while(node.children.length>1) {
    node.removeChild(node.lastChild);
   }
   // send the query
   queryUrl = "http://api.geo.admin.ch/swisssearch/geocoding?query="+place;
   this.getJSONP(queryUrl,swisstopoapi.jsoncallback);
   document.body.style.cursor = "wait";
   document.getElementById("txtInput").style.cursor = 'wait';
   //set a timeout for the request...
   swisstopoapi.timeoutid = setTimeout(function(){document.getElementById("txtInput").value = "Not found...";
      document.body.style.cursor = 'default';
      document.getElementById("txtInput").style.cursor = 'text';},10000);
}

/**
 * @description the json callback this function parses the result and sets the "search result" content
 * @param {Object} data the answer data object from geo.admin.ch
 */
swisstopoapi.jsoncallback = function(data)
{
   clearTimeout(swisstopoapi.timeoutid);
   //if no data return
   if(data.results.length==0)
   {
      document.getElementById("txtInput").value = "Not found...";
      document.body.style.cursor = 'default';
      document.getElementById("txtInput").style.cursor = 'text';
      return;
   }

   //set the searchresult-div to visible
   var divResults = document.getElementById("divSearchResults");
   divResults.style.visibility = 'visible';
   document.getElementById("divSearchResultTitle").style.visibility = 'visible';

   //parse json answer
   rawdata = data.results;

   //go trough the result array and append resultbars
   for(var i=0;i<rawdata.length;i++)
   {

      //create a resultbar and append it
      var resultbar = document.createElement('div');
      resultbar.innerHTML = rawdata[i].label;
      resultbar.id = 'divResultBar';

      resultbar.bbox = rawdata[i].bbox;
      resultbar.data = rawdata[i];

      //the onclick callback if someone clicks on a resultbar
      resultbar.onclick = function()
      {
         document.getElementById("divSearchResultTitle").style.visibility = 'hidden';
         var sr = document.getElementById("divSearchResults");
         sr.style.visibility = 'hidden';

         //fly to position
         if(this.bbox[0]==this.bbox[2] && this.bbox[1] == this.bbox[3])
         {
            var lat = CHtoWGSlat(this.bbox[0],this.bbox[1]);
            var lng = CHtoWGSlng(this.bbox[0],this.bbox[1]);

            //fly to position and set a poi
            //get the height of the position
            swisstopoapi.getJSONP("http://api.geo.admin.ch/height?easting="+this.bbox[0]+"&northing="+this.bbox[1],swisstopoapi.heightcallback);
            this.data.lat = lat;
            this.data.lng = lng;
            swisstopoapi.waitforheight.push(this.data);

         }
         else //calc the middle of the bounding box
         {
            var lat = CHtoWGSlat((this.bbox[0]+this.bbox[2])/2,(this.bbox[1]+this.bbox[3])/2);
            var lng = CHtoWGSlng((this.bbox[0]+this.bbox[2])/2,(this.bbox[1]+this.bbox[3])/2);

            // just fly to position
            var pos = ogGetOrientation(scene);
            ogFlyToLookAtPosition(scene,lng,lat,100,5000,pos.yaw,-45,0);

         }

      }

      //the search result div dissapears if a click on body occurs.
      document.body.onclick = function()
      {
         document.getElementById("divSearchResultTitle").style.visibility = 'hidden';
         var sr = document.getElementById("divSearchResults");
         sr.style.visibility = 'hidden';
         document.body.onclick = null;
      }

      //add the resultbar to the search results.
      divResults.appendChild(resultbar);
   }

   document.body.style.cursor = 'default';
   document.getElementById("txtInput").style.cursor = 'text';
}

/**
 * @description callback of a height request... not really used at the moment.
 */
swisstopoapi.heightcallback = function(data)
{
   //posdata = swisstopoapi.waitforheight.pop(rawdata[i]);
   posdata = swisstopoapi.waitforheight.pop();
   posdata.height = data.height;

  //set a poi if it's an address....
   if(posdata.service == "address")
   {
      ogChangePOIPositionWGS84(searchpoi,posdata.lng,posdata.lat,posdata.height+10);
   }

   //fly to
   var pos = ogGetOrientation(scene);
   ogFlyToLookAtPosition(scene,posdata.lng,posdata.lat,posdata.height,1000,pos.yaw,-45,0);
}


text:
<?xml version="1.0"?>
<resources>
	<set path = "sounds" />

	<sound file="success_22050_mono.ogg"/>
	<sound file="success_22050_stereo.ogg"/>
	<sound file="success_44100_mono.ogg"/>
	<sound file="success_44100_stereo.ogg"/>

	<sound file="track_22050_mono.ogg"/>
	<sound file="track_22050_stereo.ogg"/>
	<sound file="track_44100_mono.ogg" streaming="true"/>
	<sound file="track_48000_stereo.ogg"/>
	<sound file="looped.ogg"/>

	<sound file="lose_round.ogg"  streaming="true"/>
	<sound file="win_round.ogg"  streaming="true"/>
	<sound file="collect_rare.ogg"  streaming="true"/>
	<sound file="wave.wav"  streaming="true"/>
	<sound file="amb_bird_2.ogg"/>
</resources>


text:
package gw.spec.core.annotations.java;

import gw.util.StreamUtil;

import java.io.File;
import java.io.FileOutputStream;
import java.io.Writer;

public class JavaAnnotationInclusionTestGenerator
{
  static String OUTPUT_DIR = "C:\\eng\\pl\\diamond\\rough\\active\\gosu\\platform\\gosu-test\\src\\gw\\spec\\core\\annotations\\java\\";

  static String TEST_CLASS_NAME = "GeneratedJavaAnnotationInstancesTest";
  static String TEST_CLASS_ENHANCEMENTS_DIRECTLY_NAME = "GeneratedJavaAnnotationInstancesOnEnhancementDirectlyTest";
  static String TEST_CLASS_ENHANCEMENTS_THROUGH_ENHANCED_NAME = "GeneratedJavaAnnotationInstancesOnEnhancementThroughEnhancedTest";
  static String TEST_CLASS_TOP_LEVEL_CLASS_ANNOTATIONS = "GeneratedJavaAnnotationInstancesOnTopLevelClassTest";
  static String TEST_CLASS_TOP_LEVEL_INTERFACE_ANNOTATIONS = "GeneratedJavaAnnotationInstancesOnTopLevelInterfacesTest";

  static String ANNOTATION_HOLDER_CLASS_NAME = "GeneratedJavaAnnotationHolderClass";
  static String ANNOTATION_HOLDER_ENHANCEMMENT_CLASS_NAME = "GeneratedJavaAnnotationHolderClassEnhancement";

  static String TOP_LEVEL_CLASS_NAME_PREFIX = "_GeneratedTopLevelHolderClassForJava_";
  static String TOP_LEVEL_INTERFACE_NAME_PREFIX = "_GeneratedTopLevelHolderInterfaceForJava_";

  static String[][] FEATURE_DECLS = {

    {"func", "%MODIFIER% function func_%NAME%() {}", "JavaAnnotationUtil.getMethod(gsClass, \"func_%NAME%\")"},

    {"prop", "%MODIFIER% property get prop_%NAME%() : String { return null }", "JavaAnnotationUtil.getMethod(gsClass, \"getprop_%NAME%\")"},

    {"var", "%MODIFIER% var var_%NAME% : String", "gsClass.getBackingClassInfo().getDeclaredField(\"var_%NAME%\")"},

    {"var_w_prop", "%MODIFIER% var var_w_prop_%NAME% : String as var_prop_%NAME%", "JavaAnnotationUtil.getMethod(gsClass, \"getvar_prop_%NAME%\")"},

    //TODO cgross - need to ensure that modifiers are on generated setter DFS
//    {"var_w_prop_setter", "%MODIFIER% var var_w_prop_w_setter%NAME% : String as var_prop_w_setter%NAME%", "JavaAnnotationUtil.getMethod(gsClass, \"setvar_prop_w_setter%NAME%\")"},

    {"class", "%MODIFIER% class Class_%NAME%{}", "((IGosuClass) gsClass.getInnerClass(\"Class_%NAME%\")).getBackingClassInfo()"},
    {"iface", "%MODIFIER% interface Interface_%NAME%{}", "((IGosuClass) gsClass.getInnerClass(\"Interface_%NAME%\")).getBackingClassInfo()"},
  };

  static String[][] ANNOTATIONS = {
    {"simple_string", "@SingleStringAnnotation(\"foo\")",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertEquals( \"foo\", ((SingleStringAnnotation) annotations[0]).value() );\n"},

    {"simple_string_class_retention_string", "@SingleStringAnnotationClassRetention(\"foo\")",
      "    assertEquals( 0, annotations.length );"},

    {"simple_string_source_retention_string", "@SingleStringAnnotationSourceRetention(\"foo\")",
      "    assertEquals( 0, annotations.length );"},

    {"simple_int", "@SingleIntAnnotation( 42 )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertEquals( 42, ((SingleIntAnnotation) annotations[0]).value() );\n"},

    {"simple_enum", "@SingleEnumAnnotation( BAR )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertEquals( SampleEnum.BAR, ((SingleEnumAnnotation) annotations[0]).value() );\n"},

    {"simple_enum_fully_qualified", "@SingleEnumAnnotation( SampleEnum.BAR )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertEquals( SampleEnum.BAR, ((SingleEnumAnnotation) annotations[0]).value() );\n"},

    {"simple_class", "@SingleClassAnnotation( String )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertEquals( String.class, ((SingleClassAnnotation) annotations[0]).value() );\n"},

    {"simple_annotation", "@SingleAnnotationAnnotation( new SingleStringAnnotation( \"foo\" ) )",
      "    assertEquals( 1, annotations.length );\n" +
      "    SingleStringAnnotation ssa = ((SingleAnnotationAnnotation) annotations[0]).value();\n" +
      "    assertEquals( \"foo\",  ssa.value() );\n"},

    {"simple_string_array", "@SingleStringArrayAnnotation( {\"foo\", \"bar\"} )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertArrayEquals( new String[]{\"foo\", \"bar\"}, ((SingleStringArrayAnnotation) annotations[0]).value() );\n"},

    {"simple_string_array_explicit_new", "@SingleStringArrayAnnotation( new String[]{\"foo\", \"bar\"} )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertArrayEquals( new String[]{\"foo\", \"bar\"}, ((SingleStringArrayAnnotation) annotations[0]).value() );\n"},

    {"simple_string_array_no_values", "@SingleStringArrayAnnotation( new String[0] )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertArrayEquals( new String[0], ((SingleStringArrayAnnotation) annotations[0]).value() );\n"},

    {"simple_int_array", "@SingleIntArrayAnnotation( {1, 2} )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertEquals( 1, ((SingleIntArrayAnnotation) annotations[0]).value()[0] );\n"+
      "    assertEquals( 2, ((SingleIntArrayAnnotation) annotations[0]).value()[1] );\n"},

    {"simple_enum_array", "@SingleEnumArrayAnnotation( {FOO, BAR} )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertArrayEquals( new SampleEnum[]{SampleEnum.FOO, SampleEnum.BAR}, ((SingleEnumArrayAnnotation) annotations[0]).value() );\n"},

    {"simple_enum_array_fully_qualified", "@SingleEnumArrayAnnotation( {SampleEnum.FOO, SampleEnum.BAR} )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertArrayEquals( new SampleEnum[]{SampleEnum.FOO, SampleEnum.BAR}, ((SingleEnumArrayAnnotation) annotations[0]).value() );\n"},

    {"simple_class_array", "@SingleClassArrayAnnotation( {String, String} )",
      "    assertEquals( 1, annotations.length );\n" +
      "    assertArrayEquals( new Class[]{String.class, String.class}, ((SingleClassArrayAnnotation) annotations[0]).value() );\n"},

    {"simple_annotation_array", "@SingleAnnotationArrayAnnotation( {new SingleStringAnnotation( \"foo\" ), " +
                          "                                   new SingleStringAnnotation( \"bar\" )} )",
      "    assertEquals( 1, annotations.length );\n" +
      "    SingleStringAnnotation[] ssa = ((SingleAnnotationArrayAnnotation) annotations[0]).value();\n" +
      "    assertEquals( \"foo\",  ssa[0].value() );\n" +
      "    assertEquals( \"bar\",  ssa[1].value() );\n"},

  };

  static String[] ACC = {
    "",
    "public",
    "private",
    "internal",
    "protected",
  };

  static String[] STATIC = {
    "static",
    "",
  };

  public static void main( String[] args ) throws Exception
  {
    //Main holder
    writeFile( OUTPUT_DIR + ANNOTATION_HOLDER_CLASS_NAME + ".gs", generateHolderClass() );

    //Main enhancement
    writeFile( OUTPUT_DIR + ANNOTATION_HOLDER_ENHANCEMMENT_CLASS_NAME + ".gsx", generateHolderEnhancement() );

    // Main tests
    writeFile( OUTPUT_DIR + TEST_CLASS_NAME + ".java", generateTestClassForDirectAnnotationUsages() );
    writeFile( OUTPUT_DIR + TEST_CLASS_ENHANCEMENTS_DIRECTLY_NAME + ".java", generateTestClassForEnhancementAnnotationUsagesAccessedDirectly() );

    // Top Level tests
    //generateTopLevelClassHolders();
//    writeFile( OUTPUT_DIR + TEST_CLASS_TOP_LEVEL_CLASS_ANNOTATIONS + ".java", generateTestClassForTopLevelClassHolders() );

//    generateTopLevelInterfaceHolders();
//    writeFile( OUTPUT_DIR + TEST_CLASS_TOP_LEVEL_INTERFACE_ANNOTATIONS + ".java", generateTestClassForTopLevelInterfaceHolders() );
  }

//  private static String generateTestClassForTopLevelClassHolders()
//  {
//    StringBuilder sb = new StringBuilder();
//    genTestHeader( sb, TEST_CLASS_TOP_LEVEL_CLASS_ANNOTATIONS );
//    for( String[] annotationDecls : ANNOTATIONS )
//    {
//      for( String accesibility : ACC )
//      {
//        if( !accesibility.contains( "private" ) && !accesibility.contains( "protected" ) )
//        {
//          // ============================================================================
//          // regular test
//          // ============================================================================
//          String className = TOP_LEVEL_CLASS_NAME_PREFIX + annotationDecls[0] + "_" + accesibility;
//          sb.append( "  public void test" );
//          sb.append( "_" );
//          sb.append( annotationDecls[0] );
//          sb.append( "_" );
//          sb.append( accesibility );
//          sb.append( "(){\n" );
//
//          // get type
//          sb.append( "    Map<IType, List<IAnnotationInfo>> map = TypeSystem.getByFullName( \"" );
//          sb.append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() );
//          sb.append( "." );
//          sb.append( className );
//          sb.append( "\" ).getTypeInfo().getAnnotations();\n" );
//
//          // jam in the assertions
//          sb.append( annotationDecls[2] );
//
//          sb.append( "  }\n" );
//          sb.append( "\n" );
//        }
//      }
//    }
//    sb.append( "}" );
//    return sb.toString();
//  }

//  private static String generateTestClassForTopLevelInterfaceHolders()
//  {
//    StringBuilder sb = new StringBuilder();
//    genTestHeader( sb, TEST_CLASS_TOP_LEVEL_INTERFACE_ANNOTATIONS );
//    for( String[] annotationDecls : ANNOTATIONS )
//    {
//      // ============================================================================
//      // regular test
//      // ============================================================================
//      String className = TOP_LEVEL_INTERFACE_NAME_PREFIX + annotationDecls[0];
//      sb.append( "  public void test" );
//      sb.append( "_" );
//      sb.append( annotationDecls[0] );
//      sb.append( "(){\n" );
//
//      // get type
//      sb.append( "    Map<IType, List<IAnnotationInfo>> map = TypeSystem.getByFullName( \"" );
//      sb.append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() );
//      sb.append( "." );
//      sb.append( className );
//      sb.append( "\" ).getTypeInfo().getAnnotations();\n" );
//
//      // jam in the assertions
//      sb.append( annotationDecls[2] );
//
//      sb.append( "  }\n" );
//      sb.append( "\n" );
//    }
//    sb.append( "}" );
//    return sb.toString();
//  }

  private static String generateTestClassForDirectAnnotationUsages()
  {
    StringBuilder sb = new StringBuilder();
    genTestHeader( sb, TEST_CLASS_NAME );
    for( String[] annotationDecls : ANNOTATIONS )
    {
      for( String[] feature : FEATURE_DECLS )
      {
        for( String accesibility : ACC )
        {
          for( String stc : STATIC )
          {
            String modifierString = makeModifierString( accesibility, stc );
            if( modifierApplies( accesibility, feature ) )
            {
              // ============================================================================
              // regular test
              // ============================================================================
              sb.append( "  public void test" );
              sb.append( "_" );
              sb.append( annotationDecls[0] );
              sb.append( "_" );
              sb.append( modifierString );
              sb.append( "_" );
              sb.append( feature[0] );
              sb.append( "() throws Exception {\n" );

              // get type
              sb.append( "    IGosuClass gsClass = (IGosuClass) TypeSystem.getByFullName( \"" );
              sb.append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() );
              sb.append( "." );
              sb.append( ANNOTATION_HOLDER_CLASS_NAME );
              sb.append( "\" );\n" );

              // get annotations
              sb.append( "    Annotation[] annotations = " );
              sb.append( feature[2].replace( "%NAME%", annotationDecls[0] + "_" + modifierString ) );
              sb.append( ".getAnnotations();\n" );

              // jam in the assertions
              sb.append( annotationDecls[2] );

              sb.append( "  }\n" );
              sb.append( "\n" );
            }
          }
        }
      }
    }
    sb.append( "}" );
    return sb.toString();
  }

  private static String generateTestClassForEnhancementAnnotationUsagesAccessedDirectly()
  {
    StringBuilder sb = new StringBuilder();
    genTestHeader( sb, TEST_CLASS_ENHANCEMENTS_DIRECTLY_NAME );
    for( String[] annotationDecls : ANNOTATIONS )
    {
      for( String[] feature : FEATURE_DECLS )
      {
        for( String accesibility : ACC )
        {
          for( String stc : STATIC )
          {
            String modifierString = makeModifierString( accesibility, stc );
            if( modifierApplies( accesibility, feature ) )
            {
              // ============================================================================
              // enhancement features
              // ============================================================================
              if( isEnhancementFeature( feature ) )
              {

                // Verify that the annotation is on the
                sb.append( "  public void test_enhancement_directly" );
                sb.append( "_" );
                sb.append( annotationDecls[0] );
                sb.append( "_" );
                sb.append( modifierString );
                sb.append( "_" );
                sb.append( feature[0] );
                sb.append( "() throws Exception {\n" );

                // get type
                sb.append( "    IGosuClass gsClass = (IGosuClass) TypeSystem.getByFullName( \"" );
                sb.append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() );
                sb.append( "." );
                sb.append( ANNOTATION_HOLDER_ENHANCEMMENT_CLASS_NAME );
                sb.append( "\" );\n" );

                // get annotations
                sb.append( "    Annotation[] annotations = " );
                sb.append( feature[2].replace( "%NAME%", annotationDecls[0] + "_" + modifierString + "_enhancement" ) );
                sb.append( ".getAnnotations();\n" );

                // jam in the assertions
                sb.append( annotationDecls[2] );

                sb.append( "  }\n" );
                sb.append( "\n" );

              }
            }
          }
        }
      }
    }
    sb.append( "}" );
    return sb.toString();
  }

  private static String generateTestClassForEnhancementAnnotationUsagesThroughEnhanced()
  {
    StringBuilder sb = new StringBuilder();
    genTestHeader( sb, TEST_CLASS_ENHANCEMENTS_THROUGH_ENHANCED_NAME );
    for( String[] annotationDecls : ANNOTATIONS )
    {
      for( String[] feature : FEATURE_DECLS )
      {
        for( String accesibility : ACC )
        {
          for( String stc : STATIC )
          {
            String modifierString = makeModifierString( accesibility, stc );
            if( modifierApplies( accesibility, feature ) )
            {
              // ============================================================================
              // enhancement features
              // ============================================================================
              // All non-private features end up on the class as well
              if( isEnhancementFeature( feature  ) && !accesibility.contains( "private" ) )
              {
                sb.append( "  public void test_enhancement_through_enhanced" );
                sb.append( "_" );
                sb.append( annotationDecls[0] );
                sb.append( "_" );
                sb.append( modifierString );
                sb.append( "_" );
                sb.append( feature[0] );
                sb.append( "(){\n" );

                // get type
                sb.append( "    IGosuClass gsClass = (IGosuClass) TypeSystem.getByFullName( \"" );
                sb.append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() );
                sb.append( "." );
                sb.append( ANNOTATION_HOLDER_CLASS_NAME );
                sb.append( "\" );\n" );

                // get annotations
                sb.append( "    Annotation[] annotations = " );
                sb.append( feature[2].replace( "%NAME%", annotationDecls[0] + "_" + modifierString + "_enhancement" ) );
                sb.append( ".getAnnotations();\n" );

                // jam in the assertions
                sb.append( annotationDecls[2] );

                sb.append( "  }\n" );
                sb.append( "\n" );
              }            }
          }
        }
      }
    }
    sb.append( "}" );
    return sb.toString();
  }

  private static void genTestHeader( StringBuilder sb, String testName )
  {
    sb.append( "package " ).append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() ).append( ";\n" );
    sb.append( "\n" );
    sb.append( "import gw.test.TestClass;\n" );
    sb.append( "import gw.lang.*;\n" );
    sb.append( "import gw.lang.reflect.*;\n" );
    sb.append( "import gw.lang.reflect.gs.*;\n" );
    sb.append( "import java.util.*;\n" );
    sb.append( "import gw.internal.gosu.parser.GosuClass;\n" );
    sb.append( "import java.lang.annotation.Annotation;\n" );
    sb.append( "\n" );
    sb.append( "public class " ).append( testName ).append( " extends TestClass {\n" );
    sb.append( "\n" );
  }

  private static String makeModifierString( String accesibility, String stc )
  {
    return accesibility + "_" + stc;
  }

  private static boolean modifierApplies( String accesibility, String[] feature )
  {
    return accesibility.contains( "public" ) || !feature[0].contains( "iface" );
  }

  private static String generateHolderClass()
  {
    StringBuilder sb = new StringBuilder();
    sb.append( "package " ).append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() ).append( "\n" );
    sb.append( "\n" );
    sb.append( "public class " ).append( ANNOTATION_HOLDER_CLASS_NAME ).append( "{\n" );
    for( String[] annotationDecls : ANNOTATIONS )
    {
      for( String[] feature : FEATURE_DECLS )
      {
        for( String accesibility : ACC )
        {
          for( String stc : STATIC )
          {
            String modifierString = makeModifierString( accesibility, stc );
            if( modifierApplies( modifierString, feature ) )
            {
              sb.append( "  " );
              sb.append( annotationDecls[1] );
              sb.append( "\n" );
              sb.append( "  " );
              sb.append( feature[1]
                .replace( "%NAME%", annotationDecls[0] + "_" + modifierString )
                .replace( "%MODIFIER%", accesibility + " " + stc ) );
              sb.append( "\n" );
              sb.append( "\n" );
            }
          }
        }
      }
    }
    sb.append( "\n" );
    sb.append( "}" );
    return sb.toString();
  }

//  private static void generateTopLevelClassHolders() throws Exception
//  {
//    for( String[] annotationDecls : ANNOTATIONS )
//    {
//      for( String accesibility : ACC )
//      {
//        if( !accesibility.contains( "private" ) && !accesibility.contains( "protected" ) )
//        {
//          String className = TOP_LEVEL_CLASS_NAME_PREFIX + annotationDecls[0] + "_" + accesibility;
//          StringBuilder sb = new StringBuilder();
//          sb.append( "package " ).append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() ).append( "\n" );
//          sb.append( "\n" );
//          sb.append( annotationDecls[1] );
//          sb.append( "\n" );
//          sb.append( accesibility );
//          sb.append( " class " ).append( className ).append( "{}\n" );
//          String s = sb.toString();
//          writeFile( OUTPUT_DIR + className + ".gs", s );
//        }
//      }
//    }
//  }

//  private static void generateTopLevelInterfaceHolders() throws Exception
//  {
//    for( String[] annotationDecls : ANNOTATIONS )
//    {
//      String className = TOP_LEVEL_INTERFACE_NAME_PREFIX + annotationDecls[0];
//      StringBuilder sb = new StringBuilder();
//      sb.append( "package " ).append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() ).append( "\n" );
//      sb.append( "\n" );
//      sb.append( annotationDecls[1] );
//      sb.append( "\n" );
//      sb.append( "interface " ).append( className ).append( "{}\n" );
//      String s = sb.toString();
//      writeFile( OUTPUT_DIR + className + ".gs", s );
//    }
//  }

  private static String generateHolderEnhancement()
  {
    StringBuilder sb = new StringBuilder();
    sb.append( "package " ).append( JavaAnnotationInclusionTestGenerator.class.getPackage().getName() ).append( "\n" );
    sb.append( "\n" );
    sb.append( "public enhancement " );
    sb.append( ANNOTATION_HOLDER_ENHANCEMMENT_CLASS_NAME );
    sb.append( " :" );
    sb.append( ANNOTATION_HOLDER_CLASS_NAME );
    sb.append( "{\n" );
    for( String[] annotationDecls : ANNOTATIONS )
    {
      for( String[] feature : FEATURE_DECLS )
      {
        for( String accesibility : ACC )
        {
          for( String stc : STATIC )
          {
            String modifierString = makeModifierString( accesibility, stc );
            if( isEnhancementFeature( feature ) && modifierApplies( modifierString, feature ) )
            {
              sb.append( "  " );
              sb.append( annotationDecls[1] );
              sb.append( "\n" );
              sb.append( "  " );
              sb.append( feature[1]
                .replace( "%NAME%", annotationDecls[0] + "_" + modifierString + "_enhancement" )
                .replace( "%MODIFIER%", accesibility + " " + stc ) );
              sb.append( "\n" );
              sb.append( "\n" );
            }
          }
        }
      }
    }
    sb.append( "\n" );
    sb.append( "}" );
    return sb.toString();
  }

  private static boolean isEnhancementFeature( String[] feature )
  {
    String s = feature[0];
    return !(s.startsWith( "var" ) || s.startsWith( "class" ) || s.startsWith( "iface" ));
  }

  private static void writeFile( String name, String content ) throws Exception
  {
    File file = new File( name );
    if( !file.exists() )
    {
      file.createNewFile();
    }
    System.out.println( Runtime.getRuntime().exec( new String[]{"p4", "edit", name}) );
    Writer out = StreamUtil.getOutputStreamWriter( new FileOutputStream( file, false ) );
    out.write( content );
    StreamUtil.close( out );
  }
}


text:
<?php

use App\Post;
use App\Product;
use App\Term;
use Faker\Factory as Faker;
use Illuminate\Database\Seeder;

class TermablesTableSeeder extends Seeder
{
    private $faker;

    public function run()
    {
        $this->faker = Faker::create();
        $this->seedPostTermables();
        $this->seedProductTermables();
    }

    private function seedPostTermables()
    {
        $post_ids = Post::lists('id')->toArray();
        $term_ids = Term::whereIn('taxonomy', ['tag', 'category'])->lists('id')->toArray();

        foreach (range(1, 30) as $index) {
            DB::table('termables')->insert([
                'term_id'          => $this->faker->randomElement($term_ids),
                'termable_id'      => $this->faker->randomElement($post_ids),
                'termable_type'    => 'App\Post',
                ]);
        }
    }

    private function seedProductTermables()
    {
        $product_ids = Product::lists('id')->toArray();
        $term_ids = Term::whereIn('taxonomy', ['product_category'])->lists('id')->toArray();
        foreach (range(1, 30) as $index) {
            DB::table('termables')->insert([
                'term_id'          => $this->faker->randomElement($term_ids),
                'termable_id'      => $this->faker->randomElement($product_ids),
                'termable_type'    => 'App\Product',
                ]);
        }
    }
}


text:
angular.
  module('phoneDetail').
  component('phoneDetail', {
    templateUrl: 'phone-detail/phone-detail.template.html',
    controller: ['$routeParams', 'Phone',
      function PhoneDetailController($routeParams, Phone) {
        var self = this;

        self.phone = Phone.get({phoneId: $routeParams.phoneId}, function(phone){
          self.setImage(phone.images[0]);
        });

        self.setImage = function setImage(imageUrl) {
          self.mainImageUrl = imageUrl;
        };

        self.onDblclick = function onDblclick(imageUrl) {
          alert('You double-clicked image: ' + imageUrl);
        };
      }
    ]
  });


text:
using System.IO;

namespace Spect.Net.SpectrumEmu.Devices.Tape.Tzx
{
    /// <summary>
    /// This block marks the start of a group of blocks which are
    /// to be treated as one single (composite) block.
    /// </summary>
    public class TzxGroupStartDataBlock : TzxDataBlockBase
    {
        /// <summary>
        /// Number of group name
        /// </summary>
        public byte Length { get; set; }

        /// <summary>
        /// Group name bytes
        /// </summary>
        public byte[] Chars { get; set; }

        /// <summary>
        /// Gets the group name
        /// </summary>
        public string GroupName => ToAsciiString(Chars);

        /// <summary>
        /// The ID of the block
        /// </summary>
        public override int BlockId => 0x21;

        /// <summary>
        /// Reads the content of the block from the specified binary stream.
        /// </summary>
        /// <param name="reader">Stream to read the block from</param>
        public override void ReadFrom(BinaryReader reader)
        {
            Length = reader.ReadByte();
            Chars = reader.ReadBytes(Length);
        }

        /// <summary>
        /// Writes the content of the block to the specified binary stream.
        /// </summary>
        /// <param name="writer">Stream to write the block to</param>
        public override void WriteTo(BinaryWriter writer)
        {
            writer.Write(Length);
            writer.Write(Chars);
        }
    }
}


text:
package de.knightsoftnet.validators.shared.beans;

import de.knightsoftnet.validators.shared.MustBeBiggerOrEqual;

@MustBeBiggerOrEqual(field1 = "to", field2 = "from")
public class MustBeBiggerOrEqualIntegerTestBean {

  private final Integer from;

  private final Integer to;

  /**
   * constructor initializing fields.
   *
   * @param pfrom from entry
   * @param pto to entry
   */
  public MustBeBiggerOrEqualIntegerTestBean(final Integer pfrom, final Integer pto) {
    super();
    this.from = pfrom;
    this.to = pto;
  }

  public final Integer getFrom() {
    return this.from;
  }

  public final Integer getTo() {
    return this.to;
  }

  @Override
  public String toString() {
    return "MustBeBiggerOrEqualIntegerTestBean [from=" + this.from + ", to=" + this.to + "]";
  }
}


text:
import React from 'react';
import SvgIcon from '../../SvgIcon';

const NavigationArrowUpward = (props) => (
  <SvgIcon {...props}>
    <path d="M4 12l1.41 1.41L11 7.83V20h2V7.83l5.58 5.59L20 12l-8-8-8 8z"/>
  </SvgIcon>
);
NavigationArrowUpward.displayName = 'NavigationArrowUpward';
NavigationArrowUpward.muiName = 'SvgIcon';

export default NavigationArrowUpward;


text:
from __future__ import print_function

import pickle

from cart_pole import CartPole, discrete_actuator_force
from movie import make_movie

from neatsociety import nn

# load the winner
with open('nn_winner_genome', 'rb') as f:
    c = pickle.load(f)

print('Loaded genome:')
print(c)

net = nn.create_feed_forward_phenotype(c)
sim = CartPole()

print()
print("Initial conditions:")
print("        x = {0:.4f}".format(sim.x))
print("    x_dot = {0:.4f}".format(sim.dx))
print("    theta = {0:.4f}".format(sim.theta))
print("theta_dot = {0:.4f}".format(sim.dtheta))
print()

# Run the given simulation for up to 100k time steps.
num_balanced = 0
for s in range(10 ** 5):
    inputs = sim.get_scaled_state()
    action = net.serial_activate(inputs)

    # Apply action to the simulated cart-pole
    force = discrete_actuator_force(action)
    sim.step(force)

    # Stop if the network fails to keep the cart within the position or angle limits.
    # The per-run fitness is the number of time steps the network can balance the pole
    # without exceeding these limits.
    if abs(sim.x) >= sim.position_limit or abs(sim.theta) >= sim.angle_limit_radians:
        break

    num_balanced += 1

print('Pole balanced for {0:d} of 100k time steps'.format(num_balanced))

print()
print("Final conditions:")
print("        x = {0:.4f}".format(sim.x))
print("    x_dot = {0:.4f}".format(sim.dx))
print("    theta = {0:.4f}".format(sim.theta))
print("theta_dot = {0:.4f}".format(sim.dtheta))
print()
print("Making movie...")
make_movie(net, discrete_actuator_force, 15.0, "nn_movie.mp4")


text:
namespace gsimp {

// hasse diagram structures
struct hasse_node {
    std::pair< int, size_t > handle;
    std::vector< std::shared_ptr< hasse_node > > cofaces;

    hasse_node(std::pair< int, size_t > _handle) { handle = _handle; }

    void add_coface(std::shared_ptr< hasse_node >& node) {
        cofaces.push_back(node);
    }
};

struct hasse_diag {
    std::vector< std::vector< std::shared_ptr< hasse_node > > > cells;
    std::vector< std::vector< bool > > cells_c;

    hasse_diag(){};

    hasse_diag(simplicial_complex& s_comp) {
        // vector of dimension d
        for (int d = 0; d <= s_comp.dimension(); d++) {
            size_t lv_s = s_comp.get_level_size(d);
            std::vector< std::shared_ptr< hasse_node > > lv(lv_s);
            cells.push_back(lv);

            std::vector< bool > c(lv_s, false);
            cells_c.push_back(c);
        }

        for (int d = s_comp.dimension(); d > 0; d--) {
            for (size_t face_i = 0; face_i < s_comp.get_level_size(d);
                 face_i++) {
                std::shared_ptr< hasse_node > face_ptr =
                    get_face(d, face_i, true);

                std::vector< std::pair< int, size_t > > faces =
                    s_comp.get_bdry_and_ind_index(d, face_i);
                for (auto b_face_i : faces) {
                    size_t b_face = std::get< 1 >(b_face_i);
                    std::shared_ptr< hasse_node > b_face_ptr =
                        get_face(d - 1, b_face, true);
                    b_face_ptr->add_coface(face_ptr);
                }
            }
        }
        // no further need, free up the space
        cells_c.clear();
    }

    std::shared_ptr< hasse_node > get_face(int d, size_t face_i,
                                           bool building = false) {
        std::shared_ptr< hasse_node > face;
        if (building && cells_c[d][face_i])
            face = cells[d][face_i];
        else {
            if (building) cells_c[d][face_i] = true;

            cells[d][face_i] = std::make_shared< hasse_node >(
                std::pair< int, size_t >(d, face_i));
            face = cells[d][face_i];
        }
        return face;
    }

    std::vector< size_t > get_coface_i(int d, size_t face_i) {
        auto node = cells[d][face_i];
        std::vector< size_t > cofaces;
        for (auto v : node->cofaces)
            cofaces.push_back(std::get< 1 >(v->handle));
        return cofaces;
    }
};

struct simplicial_complex::impl {
    // auxiliary types
    struct SimpleOptions : Gudhi::Simplex_tree_options_full_featured {
        typedef size_t Vertex_handle;
    };

    typedef Gudhi::Simplex_tree< SimpleOptions > simp_tree;
    typedef Gudhi::Simplex_tree< SimpleOptions >::Simplex_handle simp_handle;
    typedef std::vector< simp_handle* > level_t;
    typedef std::vector< std::unique_ptr< level_t > > levels_t;

    // member variables
    std::vector< point_t > points;
    simp_tree simplices;
    std::vector< matrix_t > boundary_matrices;
    levels_t levels;

    bool has_hasse;
    hasse_diag incidence;

    impl(std::vector< point_t >& arg_points, std::vector< cell_t >& arg_tris)
        : points(arg_points) {
        // create the simplex tree
        for (auto tri : arg_tris) {
            // removed deduping to try to make this a bit faster
            // ... it did cut time down about 10%, so ...
            simplices.insert_simplex_and_subfaces(tri);
            int d = tri.size() - 1;
            if (simplices.dimension() < d) simplices.set_dimension(d);
        }

        // assign a key to each simplex in each level
        std::vector< size_t > count(simplices.dimension() + 1, 0);
        for (int i = 0; i < simplices.dimension() + 1; ++i) {
            level_t* level = new level_t();
            levels.push_back(std::unique_ptr< level_t >(level));
        }

        auto simplex_range = simplices.complex_simplex_range();
        for (auto s : simplex_range) {
            int d = simplices.dimension(s);
            simplices.assign_key(s, count[d]++);
            levels[d]->push_back(new simp_handle(s));
        }
    }

    ~impl() {
        // get rid of the levels so they won't dangle
        for (int i = levels.size(); i <= 0; --i) levels[i].reset();
    };

    size_t get_level_size(int level) { return levels[level]->size(); }

    // calculate the index of s_1 in the boundary of s_2
    int boundary_index(simp_handle s_1, simp_handle s_2) {
        auto it_1 = simplices.simplex_vertex_range(s_1).begin();
        auto end_1 = simplices.simplex_vertex_range(s_1).end();
        //
        auto it_2 = simplices.simplex_vertex_range(s_2).begin();
        //
        int orient = 0;
        int unmatch = 0;
        //
        for (int p = 0; p <= simplices.dimension(s_2); p++) {
            if (*it_1 != *it_2) {
                orient = p++;
                unmatch++;
            } else {
                if (it_1 != end_1) it_1++;
                it_2++;
            }
        }
        return pow(-1, orient);
    }

    std::vector< size_t > dedupe_vec(std::vector< size_t >& vec) {
        std::set< size_t > no_reps;
        std::vector< size_t > no_reps_list;
        for (size_t el : vec) {
            no_reps.insert(el);
        }
        for (size_t el : no_reps) {
            no_reps_list.push_back(el);
        }
        return no_reps_list;
    }

    void calculate_matrices() {
        boundary_matrices = std::vector< matrix_t >();
        for (int k = 0; k < simplices.dimension(); k++) {
            boundary_matrices.push_back(
                matrix_t(get_level_size(k), get_level_size(k + 1)));
        }
        for (auto s : simplices.complex_simplex_range()) {
            int j = simplices.key(s);
            for (auto bs : simplices.boundary_simplex_range(s)) {
                int i = simplices.key(bs);
                int k = simplices.dimension(bs);
                boundary_matrices[k].coeffRef(i, j) = boundary_index(bs, s);
            }
        }
    }

    std::vector< cell_t > get_level(int level) {
        std::vector< cell_t > level_cells;
        for (auto simp : *levels[level]) {
            cell_t v_simp;
            for (auto v : simplices.simplex_vertex_range(*simp)) {
                v_simp.push_back(v);
            }
            level_cells.push_back(v_simp);
        }
        return level_cells;
    }

    simp_handle index_to_handle(int d, size_t tau) {
        return *(*(levels[d]))[tau];
    }

    size_t handle_to_index(simp_handle tau) { return simplices.key(tau); }

    simp_handle cell_to_handle(cell_t tau) {
        auto sh = simplices.find(tau);
        return sh;
    }

    cell_t handle_to_cell(simp_handle tau) {
        cell_t cell;
        for (auto v : simplices.simplex_vertex_range(tau)) cell.push_back(v);
        return cell;
    }

};  // struct impl

std::vector< std::pair< int, cell_t > > simplicial_complex::get_bdry_and_ind(
    cell_t cell) {
    impl::simp_handle simp = p_impl->cell_to_handle(cell);
    auto c_boundary = p_impl->simplices.boundary_simplex_range(simp);
    std::vector< std::pair< int, cell_t > > boundary_and_indices;
    for (auto face : c_boundary)
        boundary_and_indices.push_back(              //
            std::make_pair< int, cell_t >(           //
                p_impl->boundary_index(face, simp),  //
                p_impl->handle_to_cell(face)));      //
    return boundary_and_indices;
};

std::vector< std::pair< int, size_t > >
simplicial_complex::get_bdry_and_ind_index(int d, size_t cell) {
    impl::simp_handle simp = p_impl->index_to_handle(d, cell);
    auto c_boundary = p_impl->simplices.boundary_simplex_range(simp);
    std::vector< std::pair< int, size_t > > boundary_and_indices;
    for (auto face : c_boundary)
        boundary_and_indices.push_back(              //
            std::make_pair< int, size_t >(           //
                p_impl->boundary_index(face, simp),  //
                p_impl->handle_to_index(face)));     //
    return boundary_and_indices;
};

std::vector< size_t > simplicial_complex::cell_boundary_index(int d,
                                                              size_t cell) {
    impl::simp_handle simp = p_impl->index_to_handle(d, cell);
    auto c_boundary = p_impl->simplices.boundary_simplex_range(simp);
    std::vector< size_t > s_boundary;
    for (auto c : c_boundary) s_boundary.push_back(p_impl->handle_to_index(c));
    return s_boundary;
}

std::vector< cell_t > simplicial_complex::cell_boundary(cell_t cell) {
    impl::simp_handle simp = p_impl->cell_to_handle(cell);
    auto c_boundary = p_impl->simplices.boundary_simplex_range(simp);
    std::vector< cell_t > s_boundary;
    for (auto c : c_boundary) s_boundary.push_back(p_impl->handle_to_cell(c));
    return s_boundary;
}

int simplicial_complex::boundary_inclusion_index(cell_t c1, cell_t c2) {
    return p_impl->boundary_index(p_impl->cell_to_handle(c1),   //
                                  p_impl->cell_to_handle(c2));  //
};
int simplicial_complex::boundary_inclusion_index(int d1, size_t s1,    //
                                                 int d2, size_t s2) {  //
    cell_t c1 = index_to_cell(d1, s1);
    cell_t c2 = index_to_cell(d2, s2);
    return p_impl->boundary_index(p_impl->cell_to_handle(c1),
                                  p_impl->cell_to_handle(c2));
};

std::vector< std::pair< int, cell_t > > simplicial_complex::get_cof_and_ind(
    cell_t cell) {
    std::vector< std::pair< int, cell_t > > c_cofaces;
    for (auto face : get_cofaces(cell))
        c_cofaces.push_back(                                   //
            std::make_pair(                                    //
                boundary_inclusion_index(cell, face), face));  //
    return c_cofaces;
}

std::vector< std::pair< int, size_t > >
simplicial_complex::get_cof_and_ind_index(int d, size_t c) {
    std::vector< std::pair< int, size_t > > c_cofaces;
    for (auto face : get_cofaces_index(d, c))
        c_cofaces.push_back(                                          //
            std::make_pair(                                           //
                boundary_inclusion_index(d, c, d + 1, face), face));  //
    return c_cofaces;
}

int simplicial_complex::get_level_size(int level) {
    return p_impl->get_level_size(level);
}

simplicial_complex::simplicial_complex(std::vector< cell_t >& arg_tris) {
    std::vector< point_t > points = {};
    p_impl = std::make_shared< impl >(points, arg_tris);
}

simplicial_complex::simplicial_complex(std::vector< point_t >& arg_points,
                                       std::vector< cell_t >& arg_tris) {
    p_impl = std::make_shared< impl >(arg_points, arg_tris);
}

simplicial_complex::simplicial_complex(const simplicial_complex& other) {
    p_impl = other.p_impl;
}

simplicial_complex& simplicial_complex::operator=(
    const simplicial_complex& other) {
    p_impl = other.p_impl;
    return *this;
}

simplicial_complex::~simplicial_complex() {}

std::vector< point_t > simplicial_complex::get_points() {
    return p_impl->points;
}

point_t simplicial_complex::get_point(size_t index) {
    return p_impl->points[index];
}

std::vector< cell_t > simplicial_complex::get_level(int level) {
    return p_impl->get_level(level);
}

matrix_t simplicial_complex::get_boundary_matrix(int d) {
    // uninstantiated boundary matrices
    if (p_impl->boundary_matrices.size() == 0) p_impl->calculate_matrices();

    // now they have to be instantiated, get them
    if (0 <= d && d < p_impl->boundary_matrices.size())
        return p_impl->boundary_matrices[d];
    else
        throw No_Boundary();
}

int simplicial_complex::dimension() { return p_impl->simplices.dimension(); }

cell_t simplicial_complex::index_to_cell(int d, size_t ind) {
    auto sh = (*(p_impl->levels[d]))[ind];
    return p_impl->handle_to_cell(*sh);
}

size_t simplicial_complex::cell_to_index(cell_t simp) {
    auto sh = p_impl->simplices.find(simp);
    return p_impl->simplices.key(sh);
}

std::vector< size_t > simplicial_complex::get_cofaces_index(int d,
                                                            size_t face) {
    // codimension 1 faces
    if (!p_impl->has_hasse) {
        calculate_hasse();
        p_impl->has_hasse = true;
    }
    auto s_cofaces = p_impl->incidence.get_coface_i(d, face);
    return s_cofaces;
}

std::vector< cell_t > simplicial_complex::get_cofaces(cell_t face) {
    if (!p_impl->has_hasse) {
        calculate_hasse();
        p_impl->has_hasse = true;
    }
    std::vector< cell_t > s_cofaces;
    auto face_i = cell_to_index(face);
    int d = face.size() - 1;
    // codimension 1 faces
    auto coface_i_v = p_impl->incidence.get_coface_i(d, face_i);
    for (auto v : coface_i_v) {
        auto face_h = (*(p_impl->levels[d + 1]))[v];
        s_cofaces.push_back(p_impl->handle_to_cell(*face_h));
    }
    return s_cofaces;
}

chain_v simplicial_complex::new_v_chain(int d) {
    std::vector< double > v(get_level_size(d), 0);
    return chain_v(d, v);
}
chain_t simplicial_complex::new_chain(int d) {
    vector_t v(get_level_size(d));
    return chain_t(d, v);
}

void simplicial_complex::calculate_hasse() {
    p_impl->has_hasse = true;
    p_impl->incidence = hasse_diag(*this);
}
};  // namespace gsimp


text:
package org.apache.xerces.jaxp;

import org.apache.xerces.impl.Constants;
import org.apache.xerces.impl.XMLErrorReporter;
import org.apache.xerces.impl.validation.ValidationManager;
import org.apache.xerces.impl.xs.XSMessageFormatter;
import org.apache.xerces.jaxp.validation.XSGrammarPoolContainer;
import org.apache.xerces.xni.grammars.XMLGrammarPool;
import org.apache.xerces.xni.parser.XMLComponentManager;
import org.apache.xerces.xni.parser.XMLConfigurationException;

/**
 *
Parser configuration for Xerces' XMLSchemaValidator.

 *
 * @version $Id$
 */
final class SchemaValidatorConfiguration implements XMLComponentManager {

    // feature identifiers

    /** Feature identifier: schema validation. */
    private static final String SCHEMA_VALIDATION =
        Constants.XERCES_FEATURE_PREFIX + Constants.SCHEMA_VALIDATION_FEATURE;

    /** Feature identifier: validation. */
    private static final String VALIDATION =
        Constants.SAX_FEATURE_PREFIX + Constants.VALIDATION_FEATURE;

    /** Feature identifier: use grammar pool only. */
    private static final String USE_GRAMMAR_POOL_ONLY =
        Constants.XERCES_FEATURE_PREFIX + Constants.USE_GRAMMAR_POOL_ONLY_FEATURE;

    /** Feature identifier: parser settings. */
    private static final String PARSER_SETTINGS =
        Constants.XERCES_FEATURE_PREFIX + Constants.PARSER_SETTINGS;

    // property identifiers

    /** Property identifier: error reporter. */
    private static final String ERROR_REPORTER =
        Constants.XERCES_PROPERTY_PREFIX + Constants.ERROR_REPORTER_PROPERTY;

    /** Property identifier: validation manager. */
    private static final String VALIDATION_MANAGER =
        Constants.XERCES_PROPERTY_PREFIX + Constants.VALIDATION_MANAGER_PROPERTY;

    /** Property identifier: grammar pool. */
    private static final String XMLGRAMMAR_POOL =
        Constants.XERCES_PROPERTY_PREFIX + Constants.XMLGRAMMAR_POOL_PROPERTY;

    //
    // Data
    //

    /** Parent component manager. **/
    private final XMLComponentManager fParentComponentManager;

    /** The Schema's grammar pool. **/
    private final XMLGrammarPool fGrammarPool;

    /**
     * Tracks whether the validator should use components from
     * the grammar pool to the exclusion of all others.
     */
    private final boolean fUseGrammarPoolOnly;

    /** Validation manager. */
    private final ValidationManager fValidationManager;

    public SchemaValidatorConfiguration(XMLComponentManager parentManager,
            XSGrammarPoolContainer grammarContainer, ValidationManager validationManager) {
        fParentComponentManager = parentManager;
        fGrammarPool = grammarContainer.getGrammarPool();
        fUseGrammarPoolOnly = grammarContainer.isFullyComposed();
        fValidationManager = validationManager;
        // add schema message formatter to error reporter
        try {
            XMLErrorReporter errorReporter = (XMLErrorReporter) fParentComponentManager.getProperty(ERROR_REPORTER);
            if (errorReporter != null) {
                errorReporter.putMessageFormatter(XSMessageFormatter.SCHEMA_DOMAIN, new XSMessageFormatter());
            }
        }
        // Ignore exception.
        catch (XMLConfigurationException exc) {}
    }

    /**
     * Returns the state of a feature.
     *
     * @param featureId The feature identifier.
     * @return true if the feature is supported
     *
     * @throws XMLConfigurationException Thrown for configuration error.
     *                                   In general, components should
     *                                   only throw this exception if
     *                                   it is really
     *                                   a critical error.
     */
    public boolean getFeature(String featureId)
            throws XMLConfigurationException {
        if (PARSER_SETTINGS.equals(featureId)) {
            return fParentComponentManager.getFeature(featureId);
        }
        else if (VALIDATION.equals(featureId) || SCHEMA_VALIDATION.equals(featureId)) {
            return true;
        }
        else if (USE_GRAMMAR_POOL_ONLY.equals(featureId)) {
            return fUseGrammarPoolOnly;
        }
        return fParentComponentManager.getFeature(featureId);
    }

    /**
     * Returns the value of a property.
     *
     * @param propertyId The property identifier.
     * @return the value of the property
     *
     * @throws XMLConfigurationException Thrown for configuration error.
     *                                   In general, components should
     *                                   only throw this exception if
     *                                   it is really
     *                                   a critical error.
     */
    public Object getProperty(String propertyId)
            throws XMLConfigurationException {
        if (XMLGRAMMAR_POOL.equals(propertyId)) {
            return fGrammarPool;
        }
        else if (VALIDATION_MANAGER.equals(propertyId)) {
            return fValidationManager;
        }
        return fParentComponentManager.getProperty(propertyId);
    }
}