text:
//
//  PGNetworkHelper+Synchronously.h
//  AFNetworking
//
//  Created by piggybear on 2017/7/25.
//

#import "PGNetworkHelper.h"

@interface PGNetworkHelper (Synchronously)
/**
 *  GET请求
 *
 *  @param URL           请求地址
 *  @param parameters    请求参数
 *  @param cache         是否缓存数据
 *  @param responseCache 缓存数据的回调
 *  @param success       请求成功的回调
 *  @param failure       请求失败的回调
 *
 *  @return 返回的对象可取消请求,调用cancle方法
 */
+ (NSURLSessionTask *)synchronouslyGET:(NSString *)URL
                            parameters:(id)parameters
                                 cache:(BOOL)cache
                         responseCache:(HttpRequestCache)responseCache
                               success:(HttpRequestSuccess)success
                               failure:(HttpRequestFailed)failure;

/**
 *  POST请求
 *
 *  @param URL           请求地址
 *  @param parameters    请求参数
 *  @param cache         是否缓存数据
 *  @param responseCache 缓存数据的回调
 *  @param success       请求成功的回调
 *  @param failure       请求失败的回调
 *
 *  @return 返回的对象可取消请求,调用cancle方法
 */
+ (NSURLSessionTask *)synchronouslyPOST:(NSString *)URL
                             parameters:(id)parameters
                                  cache:(BOOL)cache
                          responseCache:(HttpRequestCache)responseCache
                                success:(HttpRequestSuccess)success
                                failure:(HttpRequestFailed)failure;

/**
 *  上传图片文件
 *
 *  @param URL        请求地址
 *  @param parameters 请求参数
 *  @param images     图片数组
 *  @param name       文件对应服务器上的字段
 *  @param mimeType   图片文件的类型,例:png、jpeg(默认类型)....
 *  @param progress   上传进度信息
 *  @param success    请求成功的回调
 *  @param failure    请求失败的回调
 *
 *  @return 返回的对象可取消请求,调用cancle方法
 */
+ (NSURLSessionTask *)synchronouslyUploadWithURL:(NSString *)URL
                                      parameters:(NSDictionary *)parameters
                                          images:(NSArray<UIImage *> *)images
                                            name:(NSString *)name
                                        mimeType:(NSString *)mimeType
                                        progress:(HttpProgress)progress
                                         success:(HttpRequestSuccess)success
                                         failure:(HttpRequestFailed)failure;

/**
 *  下载文件
 *
 *  @param URL      请求地址
 *  @param fileDir  文件存储目录(默认存储目录为Download)
 *  @param progress 文件下载的进度信息
 *  @param success  下载成功的回调(回调参数filePath:文件的路径)
 *  @param failure  下载失败的回调
 *
 *  @return 返回NSURLSessionDownloadTask实例,可用于暂停继续,暂停调用suspend方法,开始下载调用resume方法
 */
+ (__kindof NSURLSessionTask *)synchronouslyDownloadWithURL:(NSString *)URL
                                                    fileDir:(NSString *)fileDir
                                                   progress:(HttpProgress)progress
                                                    success:(void(^)(NSString *filePath))success
                                                    failure:(HttpRequestFailed)failure;
@end


text:
package org.syphr.lametrictime.api.model.enums;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNull;

import org.junit.Test;
import org.syphr.lametrictime.api.model.enums.IconType;

public class IconTypeTest
{
    @Test
    public void testConversion()
    {
        for (IconType value : IconType.values())
        {
            assertEquals(value, IconType.toEnum(value.toRaw()));
        }
    }

    @Test
    public void testInvalidRawValue()
    {
        assertNull(IconType.toEnum("invalid raw value"));
    }

    @Test
    public void testNullRawValue()
    {
        assertNull(IconType.toEnum(null));
    }
}

redpajama_set_name: RedPajamaGithub


text:
package ch.idsia.agents.controllers;

import ch.idsia.benchmark.mario.environments.Environment;
import ch.idsia.agents.Agent;

import ch.idsia.agents.controllers.behavior.BasicTypes.*;
import ch.idsia.agents.controllers.behavior.actions.*;
import ch.idsia.agents.controllers.behavior.conditions.*;

/**
 *
 * @author lucasdavid
 */
public final class BehaviorTreeAgent extends BasicMarioAIAgent implements Agent {

    BehaviorTree behavior;
    int realJumpCounter;

    public BehaviorTreeAgent() {
        super("BehaviorTreeAgent");

        behavior = new BehaviorTree(
                new Sequence()
                .add(new StopJump())
                .add(new StopFire())
                .add(new StopMove())
                .add(
                        new Selector()
                        .add(new Sequence("EnemyFighter")
                                // iminent threat
                                .add(new NearEnemy())
                                .add(new Selector()
                                        // if mario can fight, kill threat
                                        .add(new Sequence()
                                                .add(new MarioCanFight())
                                                .add(new FightEnemy())
                                        )
                                        // jump over it, otherwise
                                        .add(new Sequence()
                                                .add(new Jump())
                                                .add(new MoveRight())
                                        )
                                )
                        )
                        // if you can move right, do it
                        .add(new Sequence("StageWalker")
                                .add(new CanMoveRight())
                                .add(new MoveRight())
                        )
                        // if there is an obstacle, jump it
                        .add(new Sequence("Jumper")
                                .add(new MoveRight())
                                .add(new Selector("ObstacleAvoider")
                                        // floating platform nearby => small jump should be executed
                                        .add(new Sequence()
                                                .add(new NearFloatingPlatform())
                                                .add(new IsGrounded())
                                                .add(new Jump())
                                                .add(new ValidJump())
                                        )
                                        // execute highest jump possible
                                        .add(new Sequence("Long jumper")
                                                .add(new Jump())
                                                .add(new ValidJump())
                                        )
                                )
                        )
                )
        );

        reset();
    }

    public boolean grounded() {
        return isMarioOnGround;
    }

    public boolean ableToJump() {
        return isMarioAbleToJump;
    }

    public int marioEgoRow() {
        return marioEgoRow;
    }

    public int marioEgoCol() {
        return marioEgoCol;
    }

    public int status() {
        return marioStatus;
    }

    public int mode() {
        return marioMode;
    }

    public byte[][] enemies() {
        return enemies;
    }

    @Override
    public void reset() {

        action = new boolean[Environment.numberOfKeys];
    }

    @Override
    public boolean[] getAction() {

        behavior.run(action, this);

        return action;
    }

}


text:
@implementation SDQueueTests

- (void)testInitialization {
    dispatch_queue_priority_t priorities[] = {
        DISPATCH_QUEUE_PRIORITY_HIGH,
        DISPATCH_QUEUE_PRIORITY_DEFAULT,
        DISPATCH_QUEUE_PRIORITY_LOW,
        DISPATCH_QUEUE_PRIORITY_BACKGROUND
    };

    STAssertNotNil([SDQueue currentQueue], @"");
    STAssertNotNil([SDQueue mainQueue], @"");
    STAssertNotNil([[SDQueue alloc] init], @"");

    for (size_t i = 0;i < sizeof(priorities) / sizeof(*priorities);++i) {
        dispatch_queue_priority_t priority = priorities[i];

        STAssertNotNil([SDQueue concurrentGlobalQueueWithPriority:priority], @"");
        STAssertNotNil([[SDQueue alloc] initWithPriority:priority], @"");
        STAssertNotNil([[SDQueue alloc] initWithPriority:priority concurrent:YES], @"");
    }
}

- (void)testSingleRecursion {
    __block BOOL finished = NO;

    SDQueue *firstQueue = [[SDQueue alloc] init];
    SDQueue *secondQueue = [[SDQueue alloc] init];

    [firstQueue runSynchronously:^{
        [secondQueue runSynchronously:^{
            [firstQueue runSynchronously:^{
                finished = YES;
            }];
        }];
    }];

    STAssertTrue(finished, @"");
}

- (void)testAsynchronousRecursion {
    __block BOOL finished = NO;

    SDQueue *firstQueue = [[SDQueue alloc] init];
    SDQueue *secondQueue = [[SDQueue alloc] init];

    [firstQueue runAsynchronously:^{
        [secondQueue runSynchronously:^{
            [firstQueue runSynchronously:^{
                [secondQueue runSynchronously:^{
                    finished = YES;
                }];
            }];
        }];
    }];

    [firstQueue runBarrierSynchronously:^{
    }];

    OSMemoryBarrier();
    STAssertTrue(finished, @"");
}

- (void)testMultipleRecursion {
    __block BOOL finished = NO;

    SDQueue *firstQueue = [[SDQueue alloc] init];
    SDQueue *secondQueue = [[SDQueue alloc] init];

    [firstQueue runSynchronously:^{
        [secondQueue runSynchronously:^{
            [SDQueue synchronizeQueues:[NSArray arrayWithObjects:firstQueue, secondQueue, nil] runSynchronously:^{
                finished = YES;
            }];
        }];
    }];

    STAssertTrue(finished, @"");
}

- (void)testPrologueEpilogue {
    __block BOOL prologueDone = NO;
    __block BOOL done = NO;
    __block BOOL epilogueDone = NO;

    SDQueue *queue = [[SDQueue alloc] init];

    queue.prologueBlock = ^{
        STAssertFalse(prologueDone, @"");
        STAssertFalse(done, @"");
        STAssertFalse(epilogueDone, @"");

        prologueDone = YES;
    };

    queue.epilogueBlock = ^{
        STAssertTrue(prologueDone, @"");
        STAssertTrue(done, @"");
        STAssertFalse(epilogueDone, @"");

        epilogueDone = YES;
    };

    [queue runSynchronously:^{
        STAssertTrue(prologueDone, @"");
        STAssertFalse(done, @"");
        STAssertFalse(epilogueDone, @"");

        done = YES;
    }];

    STAssertTrue(prologueDone, @"");
    STAssertTrue(done, @"");
    STAssertTrue(epilogueDone, @"");
}

- (void)testCurrentQueue {
    SDQueue *unitTestQueue = [SDQueue currentQueue];
    SDQueue *firstQueue = [[SDQueue alloc] init];
    SDQueue *secondQueue = [[SDQueue alloc] init];

    STAssertTrue(unitTestQueue.currentQueue, @"");

    [firstQueue runSynchronously:^{
        STAssertTrue(unitTestQueue.currentQueue, @"");
        STAssertTrue(firstQueue.currentQueue, @"");

        [secondQueue runSynchronously:^{
            STAssertTrue(unitTestQueue.currentQueue, @"");
            STAssertTrue(firstQueue.currentQueue, @"");
            STAssertTrue(secondQueue.currentQueue, @"");
        }];
    }];
}

- (void)testRunAfterDelay {
    __block BOOL finished = NO;

    SDQueue *queue = [[SDQueue alloc] init];
    [queue afterDelay:0.1 runAsynchronously:^{
        STAssertTrue(queue.currentQueue, @"");

        finished = YES;
        OSMemoryBarrier();
    }];

    STAssertFalse(finished, @"");
    [NSThread sleepForTimeInterval:0.15];
    STAssertTrue(finished, @"");
}

@end


text:
require 'action_dispatch'

module Griddler::Testing
  def upload_1
    @upload_1 ||= UploadedImage.new('photo1.jpg').file
  end

  def upload_2
    @upload_2 ||= UploadedImage.new('photo2.jpg').file
  end

  def normalize_params(params)
    Griddler::Sendgrid::Adapter.normalize_params(params)
  end

  class UploadedImage
    def initialize(name)
      @name = name
    end

    def file
      ActionDispatch::Http::UploadedFile.new({
        filename: @name,
        type: 'image/jpeg',
        tempfile: fixture_file
      })
    end

    private

    def fixture_file
      cwd = File.expand_path File.dirname(__FILE__)
      File.new(File.join(cwd, '..', '..', 'spec', 'fixtures', @name))
    end
  end
end

shared_examples_for 'Griddler adapter' do |adapter, service_params|
  it 'adapts params to expected values' do
    Griddler.configuration.email_service = adapter

    normalized_params = Griddler.configuration.email_service.normalize_params(service_params)

    Array.wrap(normalized_params).each do |params|
      email = Griddler::Email.new(params)

      email.to.should eq([{
        token: 'hi',
        host: 'example.com',
        full: 'Hello World <hi@example.com>',
        email: 'hi@example.com',
        name: 'Hello World',
      }])
      email.cc.should eq ['emily@example.com']
    end
  end
end


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using BACnet.Types;

namespace BACnet.Ashrae
{
    public partial class PropertyReference
    {
        public PropertyReference(PropertyIdentifier propertyId) : this(propertyId, Option<uint>.None)
        { }

    }
}


text:
@class MixScrollView;

@protocol MixScrollViewDataSource <NSObject>

@required
- (NSInteger)numberOfItemsInActivity:(NSInteger)activity;
- (UIView *)staticViewAtActivity:(NSInteger)activity;
- (UIView *)startViewAtActivity:(NSInteger)activity withFrame:(CGRect)frame;
- (UIView *)resultViewAtActivity:(NSInteger)activity withFrame:(CGRect)frame;

-(ItemViewCellBase *)createItemViewCell:(NSInteger)item atActivity:(NSInteger)activity reuseIdentifier:(NSString *)cellIdentifier;
-(id)dataOfItem:(NSInteger)item atActivity:(NSInteger)activity;

@optional
- (NSInteger)numberOfActivities;              // Default is 1 if not implemented

@end


text:
using System;
using System.Collections;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Text;
using System.Web;
using System.Xml;
using System.Configuration;
using umbraco.BasePages;
using umbraco.BusinessLogic;
using umbraco.businesslogic;
using umbraco.cms.businesslogic;
using umbraco.cms.businesslogic.cache;
using umbraco.cms.businesslogic.contentitem;
using umbraco.cms.businesslogic.datatype;
using umbraco.cms.businesslogic.language;
using umbraco.cms.businesslogic.media;
using umbraco.cms.businesslogic.member;
using umbraco.cms.businesslogic.property;
using umbraco.cms.businesslogic.web;
using umbraco.interfaces;
using umbraco.DataLayer;
using umbraco.BusinessLogic.Utils;
using umbraco.cms.presentation.Trees;
using Umbraco.Core.IO;
using Umbraco.Core;

namespace umbraco
{
	/// <summary>
	/// Handles loading of python items into the developer application tree
	/// </summary>
	[Obsolete("This tree is no longer shipped by default, it will be removed in the future")]
    [Tree(Constants.Applications.Developer, "python", "Python Files", sortOrder: 4)]
    public class loadPython : loadDLRScripts
	{
        public loadPython(string application) : base(application) { }
    }

}


text:
package org.apache.parquet.io;

import java.util.Arrays;
import java.util.BitSet;
import java.util.List;

import org.apache.parquet.Log;
import org.apache.parquet.column.ColumnWriteStore;
import org.apache.parquet.column.ColumnWriter;
import org.apache.parquet.column.impl.ColumnReadStoreImpl;
import org.apache.parquet.column.page.PageReadStore;
import org.apache.parquet.filter.UnboundRecordFilter;
import org.apache.parquet.filter2.compat.FilterCompat;
import org.apache.parquet.filter2.compat.FilterCompat.Filter;
import org.apache.parquet.filter2.compat.FilterCompat.FilterPredicateCompat;
import org.apache.parquet.filter2.compat.FilterCompat.NoOpFilter;
import org.apache.parquet.filter2.compat.FilterCompat.UnboundRecordFilterCompat;
import org.apache.parquet.filter2.compat.FilterCompat.Visitor;
import org.apache.parquet.filter2.predicate.FilterPredicate;
import org.apache.parquet.filter2.recordlevel.FilteringRecordMaterializer;
import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicate;
import org.apache.parquet.filter2.recordlevel.IncrementallyUpdatedFilterPredicateBuilder;
import org.apache.parquet.io.api.Binary;
import org.apache.parquet.io.api.RecordConsumer;
import org.apache.parquet.io.api.RecordMaterializer;
import org.apache.parquet.schema.MessageType;

import static org.apache.parquet.Preconditions.checkNotNull;

/**
 * Message level of the IO structure
 *
 *
 * @author Julien Le Dem
 *
 */
public class MessageColumnIO extends GroupColumnIO {
  private static final Log logger = Log.getLog(MessageColumnIO.class);

  private static final boolean DEBUG = Log.DEBUG;

  private List<PrimitiveColumnIO> leaves;

  private final boolean validating;
  private final String createdBy;

  MessageColumnIO(MessageType messageType, boolean validating, String createdBy) {
    super(messageType, null, 0);
    this.validating = validating;
    this.createdBy = createdBy;
  }

  public List<String[]> getColumnNames() {
    return super.getColumnNames();
  }

  public <T> RecordReader<T> getRecordReader(PageReadStore columns,
                                             RecordMaterializer<T> recordMaterializer) {
    return getRecordReader(columns, recordMaterializer, FilterCompat.NOOP);
  }

  /**
   * @deprecated use {@link #getRecordReader(PageReadStore, RecordMaterializer, Filter)}
   */
  @Deprecated
  public <T> RecordReader<T> getRecordReader(PageReadStore columns,
                                             RecordMaterializer<T> recordMaterializer,
                                             UnboundRecordFilter filter) {
    return getRecordReader(columns, recordMaterializer, FilterCompat.get(filter));
  }

  public <T> RecordReader<T> getRecordReader(final PageReadStore columns,
                                             final RecordMaterializer<T> recordMaterializer,
                                             final Filter filter) {
    checkNotNull(columns, "columns");
    checkNotNull(recordMaterializer, "recordMaterializer");
    checkNotNull(filter, "filter");

    if (leaves.isEmpty()) {
      return new EmptyRecordReader<T>(recordMaterializer);
    }

    return filter.accept(new Visitor<RecordReader<T>>() {
      @Override
      public RecordReader<T> visit(FilterPredicateCompat filterPredicateCompat) {

        FilterPredicate predicate = filterPredicateCompat.getFilterPredicate();
        IncrementallyUpdatedFilterPredicateBuilder builder = new IncrementallyUpdatedFilterPredicateBuilder();
        IncrementallyUpdatedFilterPredicate streamingPredicate = builder.build(predicate);
        RecordMaterializer<T> filteringRecordMaterializer = new FilteringRecordMaterializer<T>(
            recordMaterializer,
            leaves,
            builder.getValueInspectorsByColumn(),
            streamingPredicate);

        return new RecordReaderImplementation<T>(
            MessageColumnIO.this,
            filteringRecordMaterializer,
            validating,
            new ColumnReadStoreImpl(columns, filteringRecordMaterializer.getRootConverter(), getType(), createdBy));
      }

      @Override
      public RecordReader<T> visit(UnboundRecordFilterCompat unboundRecordFilterCompat) {
        return new FilteredRecordReader<T>(
            MessageColumnIO.this,
            recordMaterializer,
            validating,
            new ColumnReadStoreImpl(columns, recordMaterializer.getRootConverter(), getType(), createdBy),
            unboundRecordFilterCompat.getUnboundRecordFilter(),
            columns.getRowCount()
        );
      }

      @Override
      public RecordReader<T> visit(NoOpFilter noOpFilter) {
        return new RecordReaderImplementation<T>(
            MessageColumnIO.this,
            recordMaterializer,
            validating,
            new ColumnReadStoreImpl(columns, recordMaterializer.getRootConverter(), getType(), createdBy));
      }
    });
  }

  private class MessageColumnIORecordConsumer extends RecordConsumer {
    private ColumnIO currentColumnIO;
    private int currentLevel = 0;

    private class FieldsMarker {
      private BitSet vistedIndexes = new BitSet();

      @Override
      public String toString() {
        return "VistedIndex{" +
                "vistedIndexes=" + vistedIndexes +
                '}';
      }

      public void reset(int fieldsCount) {
        this.vistedIndexes.clear(0, fieldsCount);
      }

      public void markWritten(int i) {
        vistedIndexes.set(i);
      }

      public boolean isWritten(int i) {
        return vistedIndexes.get(i);
      }
    }

    //track at each level of depth, which fields are written, so nulls can be inserted for the unwritten fields
    private final FieldsMarker[] fieldsWritten;
    private final int[] r;
    private final ColumnWriter[] columnWriter;
    private final ColumnWriteStore columns;
    private boolean emptyField = true;

    public MessageColumnIORecordConsumer(ColumnWriteStore columns) {
      this.columns = columns;
      int maxDepth = 0;
      this.columnWriter = new ColumnWriter[MessageColumnIO.this.getLeaves().size()];
      for (PrimitiveColumnIO primitiveColumnIO : MessageColumnIO.this.getLeaves()) {
        maxDepth = Math.max(maxDepth, primitiveColumnIO.getFieldPath().length);
        columnWriter[primitiveColumnIO.getId()] = columns.getColumnWriter(primitiveColumnIO.getColumnDescriptor());
      }

      fieldsWritten = new FieldsMarker[maxDepth];
      for (int i = 0; i < maxDepth; i++) {
        fieldsWritten[i] = new FieldsMarker();
      }
      r = new int[maxDepth];
    }

    public void printState() {
      log(currentLevel + ", " + fieldsWritten[currentLevel] + ": " + Arrays.toString(currentColumnIO.getFieldPath()) + " r:" + r[currentLevel]);
      if (r[currentLevel] > currentColumnIO.getRepetitionLevel()) {
        // sanity check
        throw new InvalidRecordException(r[currentLevel] + "(r) > " + currentColumnIO.getRepetitionLevel() + " ( schema r)");
      }
    }

    private void log(Object m) {
      String indent = "";
      for (int i = 0; i<currentLevel; ++i) {
        indent += "  ";
      }
      logger.debug(indent + m);
    }

    @Override
    public void startMessage() {
      if (DEBUG) log("< MESSAGE START >");
      currentColumnIO = MessageColumnIO.this;
      r[0] = 0;
      int numberOfFieldsToVisit = ((GroupColumnIO)currentColumnIO).getChildrenCount();
      fieldsWritten[0].reset(numberOfFieldsToVisit);
      if (DEBUG) printState();
    }

    @Override
    public void endMessage() {
      writeNullForMissingFieldsAtCurrentLevel();
      columns.endRecord();
      if (DEBUG) log("< MESSAGE END >");
      if (DEBUG) printState();
    }

    @Override
    public void startField(String field, int index) {
      try {
        if (DEBUG) log("startField(" + field + ", " + index + ")");
        currentColumnIO = ((GroupColumnIO)currentColumnIO).getChild(index);
        emptyField = true;
        if (DEBUG) printState();
      } catch (RuntimeException e) {
        throw new ParquetEncodingException("error starting field " + field + " at " + index, e);
      }
    }

    @Override
    public void endField(String field, int index) {
      if (DEBUG) log("endField(" + field + ", " + index + ")");
      currentColumnIO = currentColumnIO.getParent();
      if (emptyField) {
        throw new ParquetEncodingException("empty fields are illegal, the field should be ommited completely instead");
      }
      fieldsWritten[currentLevel].markWritten(index);
      r[currentLevel] = currentLevel == 0 ? 0 : r[currentLevel - 1];
      if (DEBUG) printState();
    }

    private void writeNullForMissingFieldsAtCurrentLevel() {
      int currentFieldsCount = ((GroupColumnIO)currentColumnIO).getChildrenCount();
      for (int i = 0; i < currentFieldsCount; i++) {
        if (!fieldsWritten[currentLevel].isWritten(i)) {
          try {
            ColumnIO undefinedField = ((GroupColumnIO)currentColumnIO).getChild(i);
            int d = currentColumnIO.getDefinitionLevel();
            if (DEBUG)
              log(Arrays.toString(undefinedField.getFieldPath()) + ".writeNull(" + r[currentLevel] + "," + d + ")");
            writeNull(undefinedField, r[currentLevel], d);
          } catch (RuntimeException e) {
            throw new ParquetEncodingException("error while writing nulls for fields of indexes " + i + " . current index: " + fieldsWritten[currentLevel], e);
          }
        }
      }
    }

    private void writeNull(ColumnIO undefinedField, int r, int d) {
      if (undefinedField.getType().isPrimitive()) {
        columnWriter[((PrimitiveColumnIO)undefinedField).getId()].writeNull(r, d);
      } else {
        GroupColumnIO groupColumnIO = (GroupColumnIO)undefinedField;
        int childrenCount = groupColumnIO.getChildrenCount();
        for (int i = 0; i < childrenCount; i++) {
          writeNull(groupColumnIO.getChild(i), r, d);
        }
      }
    }

    private void setRepetitionLevel() {
      r[currentLevel] = currentColumnIO.getRepetitionLevel();
      if (DEBUG) log("r: " + r[currentLevel]);
    }

    @Override
    public void startGroup() {
      if (DEBUG) log("startGroup()");

      ++ currentLevel;
      r[currentLevel] = r[currentLevel - 1];

      int fieldsCount = ((GroupColumnIO)currentColumnIO).getChildrenCount();
      fieldsWritten[currentLevel].reset(fieldsCount);
      if (DEBUG) printState();
    }

    @Override
    public void endGroup() {
      if (DEBUG) log("endGroup()");
      emptyField = false;
      writeNullForMissingFieldsAtCurrentLevel();
      -- currentLevel;

      setRepetitionLevel();
      if (DEBUG) printState();
    }

    private ColumnWriter getColumnWriter() {
      return columnWriter[((PrimitiveColumnIO)currentColumnIO).getId()];
    }

    @Override
    public void addInteger(int value) {
      if (DEBUG) log("addInt(" + value + ")");
      emptyField = false;
      getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

      setRepetitionLevel();
      if (DEBUG) printState();
    }

    @Override
    public void addLong(long value) {
      if (DEBUG) log("addLong(" + value + ")");
      emptyField = false;
      getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

      setRepetitionLevel();
      if (DEBUG) printState();
    }

    @Override
    public void addBoolean(boolean value) {
      if (DEBUG) log("addBoolean(" + value + ")");
      emptyField = false;
      getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

      setRepetitionLevel();
      if (DEBUG) printState();
    }

    @Override
    public void addBinary(Binary value) {
      if (DEBUG) log("addBinary(" + value.length() + " bytes)");
      emptyField = false;
      getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

      setRepetitionLevel();
      if (DEBUG) printState();
    }

    @Override
    public void addFloat(float value) {
      if (DEBUG) log("addFloat(" + value + ")");
      emptyField = false;
      getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

      setRepetitionLevel();
      if (DEBUG) printState();
    }

    @Override
    public void addDouble(double value) {
      if (DEBUG) log("addDouble(" + value + ")");
      emptyField = false;
      getColumnWriter().write(value, r[currentLevel], currentColumnIO.getDefinitionLevel());

      setRepetitionLevel();
      if (DEBUG) printState();
    }

  }

  public RecordConsumer getRecordWriter(ColumnWriteStore columns) {
    RecordConsumer recordWriter = new MessageColumnIORecordConsumer(columns);
    if (DEBUG) recordWriter = new RecordConsumerLoggingWrapper(recordWriter);
    return validating ? new ValidatingRecordConsumer(recordWriter, getType()) : recordWriter;
  }

  void setLevels() {
    setLevels(0, 0, new String[0], new int[0], Arrays.<ColumnIO>asList(this), Arrays.<ColumnIO>asList(this));
  }

  void setLeaves(List<PrimitiveColumnIO> leaves) {
    this.leaves = leaves;
  }

  public List<PrimitiveColumnIO> getLeaves() {
    return this.leaves;
  }

  @Override
  public MessageType getType() {
    return (MessageType)super.getType();
  }
}


text:
namespace InControl
{
	// @cond nodoc
	[AutoDiscover]
	public class BuffaloClassicAmazonProfile : UnityInputDeviceProfile
	{
		// Right Bumper, Start and Select aren't supported.
		// Possibly they fall outside the number of buttons Unity supports?
		//
		public BuffaloClassicAmazonProfile()
		{
			Name = "Buffalo Class Gamepad";
			Meta = "Buffalo Class Gamepad on Amazon Fire TV";

			DeviceClass = InputDeviceClass.Controller;

			IncludePlatforms = new[] {
				"Amazon AFT",
			};

			JoystickNames = new[] {
				"USB,2-axis 8-button gamepad  "
			};

			ButtonMappings = new[] {
				new InputControlMapping {
					Handle = "A",
					Target = InputControlType.Action2,
					Source = Button15
				},
				new InputControlMapping {
					Handle = "B",
					Target = InputControlType.Action1,
					Source = Button16
				},
				new InputControlMapping {
					Handle = "X",
					Target = InputControlType.Action4,
					Source = Button17
				},
				new InputControlMapping {
					Handle = "Y",
					Target = InputControlType.Action3,
					Source = Button18
				},
				new InputControlMapping {
					Handle = "Left Bumper",
					Target = InputControlType.LeftBumper,
					Source = Button19
				},
//				new InputControlMapping {
//					Handle = "Right Bumper",
//					Target = InputControlType.RightBumper,
//					Source = new UnityButtonSource( 20 )
//				},
//				new InputControlMapping {
//					Handle = "Select",
//					Target = InputControlType.Select,
//					Source = Button21
//				},
//				new InputControlMapping {
//					Handle = "Start",
//					Target = InputControlType.Start,
//					Source = Button22
//				},
			};

			AnalogMappings = new[] {
				DPadLeftMapping( Analog0 ),
				DPadRightMapping( Analog0 ),
				DPadUpMapping( Analog1 ),
				DPadDownMapping( Analog1 ),
			};
		}
	}
	// @endcond
}


text:
/**
 * Adapted from
 * {@link https://github.com/Aleksandern/react-native-android-settings-library}.
 */

package org.jitsi.meet.sdk;

import android.content.ActivityNotFoundException;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Settings;

import com.facebook.react.bridge.Promise;
import com.facebook.react.bridge.ReactApplicationContext;
import com.facebook.react.bridge.ReactContextBaseJavaModule;
import com.facebook.react.bridge.ReactMethod;
import com.facebook.react.module.annotations.ReactModule;

@ReactModule(name = AndroidSettingsModule.NAME)
class AndroidSettingsModule
    extends ReactContextBaseJavaModule {

    public static final String NAME = "AndroidSettings";

    public AndroidSettingsModule(ReactApplicationContext reactContext) {
        super(reactContext);
    }

    @Override
    public String getName() {
        return NAME;
    }

    @ReactMethod
    public void open(Promise promise) {
        Context context = getReactApplicationContext();
        Intent intent = new Intent();

        intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        intent.setAction(Settings.ACTION_APPLICATION_DETAILS_SETTINGS);
        intent.setData(
            Uri.fromParts("package", context.getPackageName(), null));

        try {
            context.startActivity(intent);
        } catch (ActivityNotFoundException e) {
            // Some devices may give an error here.
            // https://developer.android.com/reference/android/provider/Settings.html#ACTION_APPLICATION_DETAILS_SETTINGS
            promise.reject(e);
            return;
        }

        promise.resolve(null);
    }
}


text:
import { StyleSheet } from 'react-native'

export default StyleSheet.create({
  container: {
    alignItems: 'center',
    paddingVertical: 26
  },
  message: {
    fontSize: 14,
    fontWeight: '500',
    color: '#333'
  }
})


text:
class CreateCodeReviewUserSettings < ActiveRecord::Migration
  def self.up
    create_table :code_review_user_settings do |t|

      t.column :user_id, :integer, :default=>0, :null => false

      t.column :mail_notification, :integer, :default=>0, :null => false

      t.column :created_at, :timestamp

      t.column :updated_at, :timestamp

    end
  end

  def self.down
    drop_table :code_review_user_settings
  end
end


text:
package org.osiam.auth.token;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.inject.Inject;

import org.osiam.resources.scim.User;
import org.springframework.security.oauth2.common.DefaultExpiringOAuth2RefreshToken;
import org.springframework.security.oauth2.common.DefaultOAuth2AccessToken;
import org.springframework.security.oauth2.common.OAuth2AccessToken;
import org.springframework.security.oauth2.provider.AuthorizationRequest;
import org.springframework.security.oauth2.provider.CompositeTokenGranter;
import org.springframework.security.oauth2.provider.OAuth2Authentication;
import org.springframework.security.oauth2.provider.TokenGranter;
import org.springframework.security.oauth2.provider.token.DefaultTokenServices;

/**
 * Custom TokenGranter, which add additional information to spring's accesstoken,
 * which the resource server needed. Iterate over all configured token granters and
 * choose the one which needed for the current authentication process.
 *
 */
public class OsiamCompositeTokenGranter extends CompositeTokenGranter {

    @Inject
    private DefaultTokenServices tokenServices;

    public OsiamCompositeTokenGranter(List<TokenGranter> tokenGranters) {
        super(tokenGranters);
    }

    public OAuth2AccessToken grant(String grantType, AuthorizationRequest authorizationRequest) {
        OAuth2AccessToken grant = super.grant(grantType, authorizationRequest);
        if (grant != null) {
            DefaultOAuth2AccessToken token = (DefaultOAuth2AccessToken) grant;
            Map<String, Object>  additionalInformation = new HashMap<String, Object>();
            additionalInformation.put("access_token", token.getValue());
            additionalInformation.put("expires_at", token.getExpiration());

            StringBuilder scopes = new StringBuilder();
            for (String scopeString : token.getScope()) {
                scopes.append(scopeString).append(" ");
            }
            additionalInformation.put("scopes", scopes);

            if(token.getRefreshToken() != null) {
                DefaultExpiringOAuth2RefreshToken refreshToken = (DefaultExpiringOAuth2RefreshToken) token.getRefreshToken();
                additionalInformation.put("refresh_token", refreshToken.getValue());
                additionalInformation.put("refresh_token_expires_at", refreshToken.getExpiration());
            }

            additionalInformation.put("token_type", token.getTokenType());
            additionalInformation.put("client_id", authorizationRequest.getClientId());

            OAuth2Authentication auth = tokenServices.loadAuthentication(token.getValue());

            if(auth.getUserAuthentication() != null && auth.getPrincipal() instanceof User) {
                User user = (User) auth.getPrincipal();
                additionalInformation.put("user_name", user.getUserName());
                additionalInformation.put("user_id", user.getId());
            }

            token.setAdditionalInformation(additionalInformation);
        }
        return grant;
    }
}


text:
package com.ericsson.otp.erlang;

import java.io.IOException;
import java.io.OutputStream;
import java.util.Random;

/**
 * Maintains a connection between a Java process and a remote Erlang, Java or C
 * node. The object maintains connection state and allows data to be sent to and
 * received from the peer.
 *
 *

 * This abstract class provides the necessary methods to maintain the actual
 * connection and encode the messages and headers in the proper format according
 * to the Erlang distribution protocol. Subclasses can use these methods to
 * provide a more or less transparent communication channel as desired.
 *

 *
 *

 * Note that no receive methods are provided. Subclasses must provide methods
 * for message delivery, and may implement their own receive methods.
 *

 *
 *

 * If an exception occurs in any of the methods in this class, the connection
 * will be closed and must be reopened in order to resume communication with the
 * peer. This will be indicated to the subclass by passing the exception to its
 * delivery() method.
 *

 *
 *

 * The System property OtpConnection.trace can be used to change the initial
 * trace level setting for all connections. Normally the initial trace level is
 * 0 and connections are not traced unless {@link #setTraceLevel
 * setTraceLevel()} is used to change the setting for a particular connection.
 * OtpConnection.trace can be used to turn on tracing by default for all
 * connections.
 *

 */
public abstract class AbstractConnection extends Thread {
    protected static final int headerLen = 2048; // more than enough

    protected static final byte passThrough = (byte) 0x70;
    protected static final byte version = (byte) 0x83;

    // Erlang message header tags
    protected static final int linkTag = 1;
    protected static final int sendTag = 2;
    protected static final int exitTag = 3;
    protected static final int unlinkTag = 4;
    protected static final int regSendTag = 6;
    protected static final int groupLeaderTag = 7;
    protected static final int exit2Tag = 8;

    protected static final int sendTTTag = 12;
    protected static final int exitTTTag = 13;
    protected static final int regSendTTTag = 16;
    protected static final int exit2TTTag = 18;

    // MD5 challenge messsage tags
    protected static final int ChallengeReply = 'r';
    protected static final int ChallengeAck = 'a';
    protected static final int ChallengeStatus = 's';

    private volatile boolean done = false;

    protected boolean connected = false; // connection status
    protected OtpTransport socket; // communication channel
    protected OtpPeer peer; // who are we connected to
    protected OtpLocalNode localNode; // this nodes id
    String name; // local name of this connection

    protected boolean cookieOk = false; // already checked the cookie for this
    // connection
    protected boolean sendCookie = true; // Send cookies in messages?

    // tracelevel constants
    protected int traceLevel = 0;

    protected static int defaultLevel = 0;
    protected static int sendThreshold = 1;
    protected static int ctrlThreshold = 2;
    protected static int handshakeThreshold = 3;

    protected static Random random = null;

    private int flags = 0;

    static {
        // trace this connection?
        final String trace = System.getProperties().getProperty(
                "OtpConnection.trace");
        try {
            if (trace != null) {
                defaultLevel = Integer.valueOf(trace).intValue();
            }
        } catch (final NumberFormatException e) {
            defaultLevel = 0;
        }
        random = new Random();
    }

    // private AbstractConnection() {
    // }

    /**
     * Accept an incoming connection from a remote node. Used by
     * {@link OtpSelf#accept() OtpSelf.accept()} to create a connection based on
     * data received when handshaking with the peer node, when the remote node
     * is the connection initiator.
     *
     * @exception java.io.IOException
     *                if it was not possible to connect to the peer.
     *
     * @exception OtpAuthException
     *                if handshake resulted in an authentication error
     */
    protected AbstractConnection(final OtpLocalNode self, final OtpTransport s)
            throws IOException, OtpAuthException {
        localNode = self;
        peer = new OtpPeer(self.transportFactory);
        socket = s;

        traceLevel = defaultLevel;
        setDaemon(true);

        if (traceLevel >= handshakeThreshold) {
            System.out.println("<- ACCEPT FROM " + s);
        }

        // get his info
        recvName(peer);

        // now find highest common dist value
        if (peer.proto != self.proto || self.distHigh < peer.distLow
                || self.distLow > peer.distHigh) {
            close();
            throw new IOException(
                    "No common protocol found - cannot accept connection");
        }
        // highest common version: min(peer.distHigh, self.distHigh)
        peer.distChoose = peer.distHigh > self.distHigh ? self.distHigh
                : peer.distHigh;

        doAccept();
        name = peer.node();
    }

    /**
     * Intiate and open a connection to a remote node.
     *
     * @exception java.io.IOException
     *                if it was not possible to connect to the peer.
     *
     * @exception OtpAuthException
     *                if handshake resulted in an authentication error.
     */
    protected AbstractConnection(final OtpLocalNode self, final OtpPeer other)
            throws IOException, OtpAuthException {
        peer = other;
        localNode = self;
        socket = null;
        int port;

        traceLevel = defaultLevel;
        setDaemon(true);

        // now get a connection between the two...
        port = OtpEpmd.lookupPort(peer);
        if (port == 0)
            throw new IOException("No remote node found - cannot connect");

        // now find highest common dist value
        if (peer.proto != self.proto || self.distHigh < peer.distLow
                || self.distLow > peer.distHigh) {
            throw new IOException("No common protocol found - cannot connect");
        }

        // highest common version: min(peer.distHigh, self.distHigh)
        peer.distChoose = peer.distHigh > self.distHigh ? self.distHigh
                : peer.distHigh;

        doConnect(port);

        name = peer.node();
        connected = true;
    }

    /**
     * Deliver communication exceptions to the recipient.
     */
    public abstract void deliver(Exception e);

    /**
     * Deliver messages to the recipient.
     */
    public abstract void deliver(OtpMsg msg);

    /**
     * Send a pre-encoded message to a named process on a remote node.
     *
     * @param dest
     *            the name of the remote process.
     * @param payload
     *            the encoded message to send.
     *
     * @exception java.io.IOException
     *                if the connection is not active or a communication error
     *                occurs.
     */
    protected void sendBuf(final OtpErlangPid from, final String dest,
            final OtpOutputStream payload) throws IOException {
        if (!connected) {
            throw new IOException("Not connected");
        }
        @SuppressWarnings("resource")
        final OtpOutputStream header = new OtpOutputStream(headerLen);

        // preamble: 4 byte length + "passthrough" tag + version
        header.write4BE(0); // reserve space for length
        header.write1(passThrough);
        header.write1(version);

        // header info
        header.write_tuple_head(4);
        header.write_long(regSendTag);
        header.write_any(from);
        if (sendCookie) {
            header.write_atom(localNode.cookie());
        } else {
            header.write_atom("");
        }
        header.write_atom(dest);

        // version for payload
        header.write1(version);

        // fix up length in preamble
        header.poke4BE(0, header.size() + payload.size() - 4);

        do_send(header, payload);
    }

    /**
     * Send a pre-encoded message to a process on a remote node.
     *
     * @param dest
     *            the Erlang PID of the remote process.
     * @param payload
     *            the encoded message to send.
     *
     * @exception java.io.IOException
     *                if the connection is not active or a communication error
     *                occurs.
     */
    protected void sendBuf(final OtpErlangPid from, final OtpErlangPid dest,
            final OtpOutputStream payload) throws IOException {
        if (!connected) {
            throw new IOException("Not connected");
        }
        @SuppressWarnings("resource")
        final OtpOutputStream header = new OtpOutputStream(headerLen);

        // preamble: 4 byte length + "passthrough" tag + version
        header.write4BE(0); // reserve space for length
        header.write1(passThrough);
        header.write1(version);

        // header info
        header.write_tuple_head(3);
        header.write_long(sendTag);
        if (sendCookie) {
            header.write_atom(localNode.cookie());
        } else {
            header.write_atom("");
        }
        header.write_any(dest);

        // version for payload
        header.write1(version);

        // fix up length in preamble
        header.poke4BE(0, header.size() + payload.size() - 4);

        do_send(header, payload);
    }

    /*
     * Send an auth error to peer because he sent a bad cookie. The auth error
     * uses his cookie (not revealing ours). This is just like send_reg
     * otherwise
     */
    private void cookieError(final OtpLocalNode local,
            final OtpErlangAtom cookie) throws OtpAuthException {
        try {
            @SuppressWarnings("resource")
            final OtpOutputStream header = new OtpOutputStream(headerLen);

            // preamble: 4 byte length + "passthrough" tag + version
            header.write4BE(0); // reserve space for length
            header.write1(passThrough);
            header.write1(version);

            header.write_tuple_head(4);
            header.write_long(regSendTag);
            header.write_any(local.createPid()); // disposable pid
            header.write_atom(cookie.atomValue()); // important: his cookie,
            // not mine...
            header.write_atom("auth");

            // version for payload
            header.write1(version);

            // the payload

            // the no_auth message (copied from Erlang) Don't change this
            // (Erlang will crash)
            // {$gen_cast, {print, "~n** Unauthorized cookie ~w **~n",
            // [foo@aule]}}
            final OtpErlangObject[] msg = new OtpErlangObject[2];
            final OtpErlangObject[] msgbody = new OtpErlangObject[3];

            msgbody[0] = new OtpErlangAtom("print");
            msgbody[1] = new OtpErlangString("~n** Bad cookie sent to " + local
                    + " **~n");
            // Erlang will crash and burn if there is no third argument here...
            msgbody[2] = new OtpErlangList(); // empty list

            msg[0] = new OtpErlangAtom("$gen_cast");
            msg[1] = new OtpErlangTuple(msgbody);

            @SuppressWarnings("resource")
            final OtpOutputStream payload = new OtpOutputStream(
                    new OtpErlangTuple(msg));

            // fix up length in preamble
            header.poke4BE(0, header.size() + payload.size() - 4);

            try {
                do_send(header, payload);
            } catch (final IOException e) {
            } // ignore
        } finally {
            close();
        }
        throw new OtpAuthException("Remote cookie not authorized: "
                + cookie.atomValue());
    }

    // link to pid

    /**
     * Create a link between the local node and the specified process on the
     * remote node. If the link is still active when the remote process
     * terminates, an exit signal will be sent to this connection. Use
     * {@link #sendUnlink unlink()} to remove the link.
     *
     * @param dest
     *            the Erlang PID of the remote process.
     *
     * @exception java.io.IOException
     *                if the connection is not active or a communication error
     *                occurs.
     */
    protected void sendLink(final OtpErlangPid from, final OtpErlangPid dest)
            throws IOException {
        if (!connected) {
            throw new IOException("Not connected");
        }
        @SuppressWarnings("resource")
        final OtpOutputStream header = new OtpOutputStream(headerLen);

        // preamble: 4 byte length + "passthrough" tag
        header.write4BE(0); // reserve space for length
        header.write1(passThrough);
        header.write1(version);

        // header
        header.write_tuple_head(3);
        header.write_long(linkTag);
        header.write_any(from);
        header.write_any(dest);

        // fix up length in preamble
        header.poke4BE(0, header.size() - 4);

        do_send(header);
    }

    /**
     * Remove a link between the local node and the specified process on the
     * remote node. This method deactivates links created with {@link #sendLink
     * link()}.
     *
     * @param dest
     *            the Erlang PID of the remote process.
     *
     * @exception java.io.IOException
     *                if the connection is not active or a communication error
     *                occurs.
     */
    protected void sendUnlink(final OtpErlangPid from, final OtpErlangPid dest)
            throws IOException {
        if (!connected) {
            throw new IOException("Not connected");
        }
        @SuppressWarnings("resource")
        final OtpOutputStream header = new OtpOutputStream(headerLen);

        // preamble: 4 byte length + "passthrough" tag
        header.write4BE(0); // reserve space for length
        header.write1(passThrough);
        header.write1(version);

        // header
        header.write_tuple_head(3);
        header.write_long(unlinkTag);
        header.write_any(from);
        header.write_any(dest);

        // fix up length in preamble
        header.poke4BE(0, header.size() - 4);

        do_send(header);
    }

    /* used internally when "processes" terminate */
    protected void sendExit(final OtpErlangPid from, final OtpErlangPid dest,
            final OtpErlangObject reason) throws IOException {
        sendExit(exitTag, from, dest, reason);
    }

    /**
     * Send an exit signal to a remote process.
     *
     * @param dest
     *            the Erlang PID of the remote process.
     * @param reason
     *            an Erlang term describing the exit reason.
     *
     * @exception java.io.IOException
     *                if the connection is not active or a communication error
     *                occurs.
     */
    protected void sendExit2(final OtpErlangPid from, final OtpErlangPid dest,
            final OtpErlangObject reason) throws IOException {
        sendExit(exit2Tag, from, dest, reason);
    }

    private void sendExit(final int tag, final OtpErlangPid from,
            final OtpErlangPid dest, final OtpErlangObject reason)
            throws IOException {
        if (!connected) {
            throw new IOException("Not connected");
        }
        @SuppressWarnings("resource")
        final OtpOutputStream header = new OtpOutputStream(headerLen);

        // preamble: 4 byte length + "passthrough" tag
        header.write4BE(0); // reserve space for length
        header.write1(passThrough);
        header.write1(version);

        // header
        header.write_tuple_head(4);
        header.write_long(tag);
        header.write_any(from);
        header.write_any(dest);
        header.write_any(reason);

        // fix up length in preamble
        header.poke4BE(0, header.size() - 4);

        do_send(header);
    }

    @SuppressWarnings("resource")
    @Override
    public void run() {
        if (!connected) {
            deliver(new IOException("Not connected"));
            return;
        }

        final byte[] lbuf = new byte[4];
        OtpInputStream ibuf;
        OtpErlangObject traceobj;
        int len;
        final byte[] tock = { 0, 0, 0, 0 };

        try {
            receive_loop: while (!done) {
                // don't return until we get a real message
                // or a failure of some kind (e.g. EXIT)
                // read length and read buffer must be atomic!
                do {
                    // read 4 bytes - get length of incoming packet
                    // socket.getInputStream().read(lbuf);
                    readSock(socket, lbuf);
                    ibuf = new OtpInputStream(lbuf, flags);
                    len = ibuf.read4BE();

                    // received tick? send tock!
                    if (len == 0) {
                        synchronized (this) {
                            OutputStream out = socket.getOutputStream();
                            out.write(tock);
                            out.flush();
                        }
                    }

                } while (len == 0); // tick_loop

                // got a real message (maybe) - read len bytes
                final byte[] tmpbuf = new byte[len];
                // i = socket.getInputStream().read(tmpbuf);
                readSock(socket, tmpbuf);
                ibuf.close();
                ibuf = new OtpInputStream(tmpbuf, flags);

                if (ibuf.read1() != passThrough) {
                    break receive_loop;
                }

                // got a real message (really)
                OtpErlangObject reason = null;
                OtpErlangAtom cookie = null;
                OtpErlangObject tmp = null;
                OtpErlangTuple head = null;
                OtpErlangAtom toName;
                OtpErlangPid to;
                OtpErlangPid from;
                int tag;

                // decode the header
                tmp = ibuf.read_any();
                if (!(tmp instanceof OtpErlangTuple)) {
                    break receive_loop;
                }

                head = (OtpErlangTuple) tmp;
                if (!(head.elementAt(0) instanceof OtpErlangLong)) {
                    break receive_loop;
                }

                // lets see what kind of message this is
                tag = (int) ((OtpErlangLong) head.elementAt(0)).longValue();

                switch (tag) {
                case sendTag: // { SEND, Cookie, ToPid }
                case sendTTTag: // { SEND, Cookie, ToPid, TraceToken }
                    if (!cookieOk) {
                        // we only check this once, he can send us bad cookies
                        // later if he likes
                        if (!(head.elementAt(1) instanceof OtpErlangAtom)) {
                            break receive_loop;
                        }
                        cookie = (OtpErlangAtom) head.elementAt(1);
                        if (sendCookie) {
                            if (!cookie.atomValue().equals(localNode.cookie())) {
                                cookieError(localNode, cookie);
                            }
                        } else {
                            if (!cookie.atomValue().equals("")) {
                                cookieError(localNode, cookie);
                            }
                        }
                        cookieOk = true;
                    }

                    if (traceLevel >= sendThreshold) {
                        System.out.println("<- " + headerType(head) + " "
                                + head);

                        /* show received payload too */
                        ibuf.mark(0);
                        traceobj = ibuf.read_any();

                        if (traceobj != null) {
                            System.out.println("   " + traceobj);
                        } else {
                            System.out.println("   (null)");
                        }
                        ibuf.reset();
                    }

                    to = (OtpErlangPid) head.elementAt(2);

                    deliver(new OtpMsg(to, ibuf));
                    break;

                case regSendTag: // { REG_SEND, FromPid, Cookie, ToName }
                case regSendTTTag: // { REG_SEND, FromPid, Cookie, ToName,
                    // TraceToken }
                    if (!cookieOk) {
                        // we only check this once, he can send us bad cookies
                        // later if he likes
                        if (!(head.elementAt(2) instanceof OtpErlangAtom)) {
                            break receive_loop;
                        }
                        cookie = (OtpErlangAtom) head.elementAt(2);
                        if (sendCookie) {
                            if (!cookie.atomValue().equals(localNode.cookie())) {
                                cookieError(localNode, cookie);
                            }
                        } else {
                            if (!cookie.atomValue().equals("")) {
                                cookieError(localNode, cookie);
                            }
                        }
                        cookieOk = true;
                    }

                    if (traceLevel >= sendThreshold) {
                        System.out.println("<- " + headerType(head) + " "
                                + head);

                        /* show received payload too */
                        ibuf.mark(0);
                        traceobj = ibuf.read_any();

                        if (traceobj != null) {
                            System.out.println("   " + traceobj);
                        } else {
                            System.out.println("   (null)");
                        }
                        ibuf.reset();
                    }

                    from = (OtpErlangPid) head.elementAt(1);
                    toName = (OtpErlangAtom) head.elementAt(3);

                    deliver(new OtpMsg(from, toName.atomValue(), ibuf));
                    break;

                case exitTag: // { EXIT, FromPid, ToPid, Reason }
                case exit2Tag: // { EXIT2, FromPid, ToPid, Reason }
                    if (head.elementAt(3) == null) {
                        break receive_loop;
                    }
                    if (traceLevel >= ctrlThreshold) {
                        System.out.println("<- " + headerType(head) + " "
                                + head);
                    }

                    from = (OtpErlangPid) head.elementAt(1);
                    to = (OtpErlangPid) head.elementAt(2);
                    reason = head.elementAt(3);

                    deliver(new OtpMsg(tag, from, to, reason));
                    break;

                case exitTTTag: // { EXIT, FromPid, ToPid, TraceToken, Reason }
                case exit2TTTag: // { EXIT2, FromPid, ToPid, TraceToken,
                    // Reason
                    // }
                    // as above, but bifferent element number
                    if (head.elementAt(4) == null) {
                        break receive_loop;
                    }
                    if (traceLevel >= ctrlThreshold) {
                        System.out.println("<- " + headerType(head) + " "
                                + head);
                    }

                    from = (OtpErlangPid) head.elementAt(1);
                    to = (OtpErlangPid) head.elementAt(2);
                    reason = head.elementAt(4);

                    deliver(new OtpMsg(tag, from, to, reason));
                    break;

                case linkTag: // { LINK, FromPid, ToPid}
                case unlinkTag: // { UNLINK, FromPid, ToPid}
                    if (traceLevel >= ctrlThreshold) {
                        System.out.println("<- " + headerType(head) + " "
                                + head);
                    }

                    from = (OtpErlangPid) head.elementAt(1);
                    to = (OtpErlangPid) head.elementAt(2);

                    deliver(new OtpMsg(tag, from, to));
                    break;

                // absolutely no idea what to do with these, so we ignore
                // them...
                case groupLeaderTag: // { GROUPLEADER, FromPid, ToPid}
                    // (just show trace)
                    if (traceLevel >= ctrlThreshold) {
                        System.out.println("<- " + headerType(head) + " "
                                + head);
                    }
                    break;

                default:
                    // garbage?
                    break receive_loop;
                }
            } // end receive_loop

            // this section reachable only with break
            // we have received garbage from peer
            deliver(new OtpErlangExit("Remote is sending garbage"));

        } // try

        catch (final OtpAuthException e) {
            deliver(e);
        } catch (final OtpErlangDecodeException e) {
            deliver(new OtpErlangExit("Remote is sending garbage"));
        } catch (final IOException e) {
            deliver(new OtpErlangExit("Remote has closed connection"));
        } finally {
            close();
        }
    }

    /**
     *

     * Set the trace level for this connection. Normally tracing is off by
     * default unless System property OtpConnection.trace was set.
     *

     *
     *

     * The following levels are valid: 0 turns off tracing completely, 1 shows
     * ordinary send and receive messages, 2 shows control messages such as link
     * and unlink, 3 shows handshaking at connection setup, and 4 shows
     * communication with Epmd. Each level includes the information shown by the
     * lower ones.
     *

     *
     * @param level
     *            the level to set.
     *
     * @return the previous trace level.
     */
    public int setTraceLevel(final int level) {
        final int oldLevel = traceLevel;

        // pin the value
        int theLevel = level;
        if (level < 0) {
            theLevel = 0;
        } else if (level > 4) {
            theLevel = 4;
        }

        traceLevel = theLevel;

        return oldLevel;
    }

    /**
     * Get the trace level for this connection.
     *
     * @return the current trace level.
     */
    public int getTraceLevel() {
        return traceLevel;
    }

    /**
     * Close the connection to the remote node.
     */
    public void close() {
        done = true;
        connected = false;
        synchronized (this) {
            try {
                if (socket != null) {
                    if (traceLevel >= ctrlThreshold) {
                        System.out.println("-> CLOSE");
                    }
                    socket.close();
                }
            } catch (final IOException e) { /* ignore socket close errors */
            } finally {
                socket = null;
            }
        }
    }

    @Override
    protected void finalize() {
        close();
    }

    /**
     * Determine if the connection is still alive. Note that this method only
     * reports the status of the connection, and that it is possible that there
     * are unread messages waiting in the receive queue.
     *
     * @return true if the connection is alive.
     */
    public boolean isConnected() {
        return connected;
    }

    // used by send and send_reg (message types with payload)
    protected synchronized void do_send(final OtpOutputStream header,
            final OtpOutputStream payload) throws IOException {
        try {
            if (traceLevel >= sendThreshold) {
                // Need to decode header and output buffer to show trace
                // message!
                // First make OtpInputStream, then decode.
                try {
                    final OtpErlangObject h = header.getOtpInputStream(5)
                            .read_any();
                    System.out.println("-> " + headerType(h) + " " + h);

                    OtpErlangObject o = payload.getOtpInputStream(0).read_any();
                    System.out.println("   " + o);
                    o = null;
                } catch (final OtpErlangDecodeException e) {
                    System.out.println("   " + "can't decode output buffer:"
                            + e);
                }
            }

            // group flush op in favour of possible ssh-tunneled stream
            OutputStream out = socket.getOutputStream();
            header.writeTo(out);
            payload.writeTo(out);
            out.flush();
        } catch (final IOException e) {
            close();
            throw e;
        }
    }

    // used by the other message types
    protected synchronized void do_send(final OtpOutputStream header)
            throws IOException {
        try {
            if (traceLevel >= ctrlThreshold) {
                try {
                    final OtpErlangObject h = header.getOtpInputStream(5)
                            .read_any();
                    System.out.println("-> " + headerType(h) + " " + h);
                } catch (final OtpErlangDecodeException e) {
                    System.out.println("   " + "can't decode output buffer: "
                            + e);
                }
            }
            header.writeToAndFlush(socket.getOutputStream());
        } catch (final IOException e) {
            close();
            throw e;
        }
    }

    protected String headerType(final OtpErlangObject h) {
        int tag = -1;

        if (h instanceof OtpErlangTuple) {
            tag = (int) ((OtpErlangLong) ((OtpErlangTuple) h).elementAt(0))
                    .longValue();
        }

        switch (tag) {
        case linkTag:
            return "LINK";

        case sendTag:
            return "SEND";

        case exitTag:
            return "EXIT";

        case unlinkTag:
            return "UNLINK";

        case regSendTag:
            return "REG_SEND";

        case groupLeaderTag:
            return "GROUP_LEADER";

        case exit2Tag:
            return "EXIT2";

        case sendTTTag:
            return "SEND_TT";

        case exitTTTag:
            return "EXIT_TT";

        case regSendTTTag:
            return "REG_SEND_TT";

        case exit2TTTag:
            return "EXIT2_TT";
        }

        return "(unknown type)";
    }

    /* this method now throws exception if we don't get full read */
    protected int readSock(final OtpTransport s, final byte[] b)
            throws IOException {
        int got = 0;
        final int len = b.length;
        int i;

        synchronized (this) {
            if (s == null) {
                throw new IOException("expected " + len
                        + " bytes, socket was closed");
            }
        }

        while (got < len) {
            i = s.getInputStream().read(b, got, len - got);

            if (i < 0) {
                throw new IOException("expected " + len
                        + " bytes, got EOF after " + got + " bytes");
            } else if (i == 0 && len != 0) {
                /*
                 * This is a corner case. According to
                 * http://java.sun.com/j2se/1.4.2/docs/api/ class InputStream
                 * is.read(,,l) can only return 0 if l==0. In other words it
                 * should not happen, but apparently did.
                 */
                throw new IOException("Remote connection closed");
            } else {
                got += i;
            }
        }
        return got;
    }

    protected void doAccept() throws IOException, OtpAuthException {
        try {
            sendStatus("ok");
            final int our_challenge = genChallenge();
            sendChallenge(peer.distChoose, localNode.flags, our_challenge);
            final int her_challenge = recvChallengeReply(our_challenge);
            final byte[] our_digest = genDigest(her_challenge,
                    localNode.cookie());
            sendChallengeAck(our_digest);
            connected = true;
            cookieOk = true;
            sendCookie = false;
        } catch (final IOException ie) {
            close();
            throw ie;
        } catch (final OtpAuthException ae) {
            close();
            throw ae;
        } catch (final Exception e) {
            final String nn = peer.node();
            close();
            final IOException ioe = new IOException(
                    "Error accepting connection from " + nn);
            ioe.initCause(e);
            throw ioe;
        }
        if (traceLevel >= handshakeThreshold) {
            System.out.println("<- MD5 ACCEPTED " + peer.host());
        }
    }

    protected void doConnect(final int port) throws IOException,
            OtpAuthException {
        try {
            socket = peer.createTransport(peer.host(), port);

            if (traceLevel >= handshakeThreshold) {
                System.out.println("-> MD5 CONNECT TO " + peer.host() + ":"
                        + port);
            }
            sendName(peer.distChoose, localNode.flags);
            recvStatus();
            final int her_challenge = recvChallenge();
            final byte[] our_digest = genDigest(her_challenge,
                    localNode.cookie());
            final int our_challenge = genChallenge();
            sendChallengeReply(our_challenge, our_digest);
            recvChallengeAck(our_challenge);
            cookieOk = true;
            sendCookie = false;
        } catch (final OtpAuthException ae) {
            close();
            throw ae;
        } catch (final Exception e) {
            close();
            final IOException ioe = new IOException(
                    "Cannot connect to peer node");
            ioe.initCause(e);
            throw ioe;
        }
    }

    // This is nooo good as a challenge,
    // XXX fix me.
    static protected int genChallenge() {
        return random.nextInt();
    }

    // Used to debug print a message digest
    static String hex0(final byte x) {
        final char tab[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9',
                'a', 'b', 'c', 'd', 'e', 'f' };
        int uint;
        if (x < 0) {
            uint = x & 0x7F;
            uint |= 1 << 7;
        } else {
            uint = x;
        }
        return "" + tab[uint >>> 4] + tab[uint & 0xF];
    }

    static String hex(final byte[] b) {
        final StringBuffer sb = new StringBuffer();
        try {
            int i;
            for (i = 0; i < b.length; ++i) {
                sb.append(hex0(b[i]));
            }
        } catch (final Exception e) {
            // Debug function, ignore errors.
        }
        return sb.toString();

    }

    protected byte[] genDigest(final int challenge, final String cookie) {
        int i;
        long ch2;

        if (challenge < 0) {
            ch2 = 1L << 31;
            ch2 |= challenge & 0x7FFFFFFF;
        } else {
            ch2 = challenge;
        }
        final OtpMD5 context = new OtpMD5();
        context.update(cookie);
        context.update("" + ch2);

        final int[] tmp = context.final_bytes();
        final byte[] res = new byte[tmp.length];
        for (i = 0; i < tmp.length; ++i) {
            res[i] = (byte) (tmp[i] & 0xFF);
        }
        return res;
    }

    protected void sendName(final int dist, final int aflags)
            throws IOException {

        @SuppressWarnings("resource")
        final OtpOutputStream obuf = new OtpOutputStream();
        final String str = localNode.node();
        obuf.write2BE(str.length() + 7); // 7 bytes + nodename
        obuf.write1(AbstractNode.NTYPE_R6);
        obuf.write2BE(dist);
        obuf.write4BE(aflags);
        obuf.write(str.getBytes());

        obuf.writeToAndFlush(socket.getOutputStream());

        if (traceLevel >= handshakeThreshold) {
            System.out.println("-> " + "HANDSHAKE sendName" + " flags="
                    + aflags + " dist=" + dist + " local=" + localNode);
        }
    }

    protected void sendChallenge(final int dist, final int aflags,
            final int challenge) throws IOException {

        @SuppressWarnings("resource")
        final OtpOutputStream obuf = new OtpOutputStream();
        final String str = localNode.node();
        obuf.write2BE(str.length() + 11); // 11 bytes + nodename
        obuf.write1(AbstractNode.NTYPE_R6);
        obuf.write2BE(dist);
        obuf.write4BE(aflags);
        obuf.write4BE(challenge);
        obuf.write(str.getBytes());

        obuf.writeToAndFlush(socket.getOutputStream());

        if (traceLevel >= handshakeThreshold) {
            System.out.println("-> " + "HANDSHAKE sendChallenge" + " flags="
                    + aflags + " dist=" + dist + " challenge=" + challenge
                    + " local=" + localNode);
        }
    }

    protected byte[] read2BytePackage() throws IOException,
            OtpErlangDecodeException {

        final byte[] lbuf = new byte[2];
        byte[] tmpbuf;

        readSock(socket, lbuf);
        @SuppressWarnings("resource")
        final OtpInputStream ibuf = new OtpInputStream(lbuf, 0);
        final int len = ibuf.read2BE();
        tmpbuf = new byte[len];
        readSock(socket, tmpbuf);
        return tmpbuf;
    }

    protected void recvName(final OtpPeer apeer) throws IOException {

        String hisname = "";

        try {
            final byte[] tmpbuf = read2BytePackage();
            @SuppressWarnings("resource")
            final OtpInputStream ibuf = new OtpInputStream(tmpbuf, 0);
            byte[] tmpname;
            final int len = tmpbuf.length;
            apeer.ntype = ibuf.read1();
            if (apeer.ntype != AbstractNode.NTYPE_R6) {
                throw new IOException("Unknown remote node type");
            }
            apeer.distLow = apeer.distHigh = ibuf.read2BE();
            if (apeer.distLow < 5) {
                throw new IOException("Unknown remote node type");
            }
            apeer.flags = ibuf.read4BE();
            tmpname = new byte[len - 7];
            ibuf.readN(tmpname);
            hisname = OtpErlangString.newString(tmpname);
            // Set the old nodetype parameter to indicate hidden/normal status
            // When the old handshake is removed, the ntype should also be.
            if ((apeer.flags & AbstractNode.dFlagPublished) != 0) {
                apeer.ntype = AbstractNode.NTYPE_R4_ERLANG;
            } else {
                apeer.ntype = AbstractNode.NTYPE_R4_HIDDEN;
            }

            if ((apeer.flags & AbstractNode.dFlagExtendedReferences) == 0) {
                throw new IOException(
                        "Handshake failed - peer cannot handle extended references");
            }

            if ((apeer.flags & AbstractNode.dFlagExtendedPidsPorts) == 0) {
                throw new IOException(
                        "Handshake failed - peer cannot handle extended pids and ports");
            }

        } catch (final OtpErlangDecodeException e) {
            throw new IOException("Handshake failed - not enough data");
        }

        final int i = hisname.indexOf('@', 0);
        apeer.node = hisname;
        apeer.alive = hisname.substring(0, i);
        apeer.host = hisname.substring(i + 1, hisname.length());

        if (traceLevel >= handshakeThreshold) {
            System.out.println("<- " + "HANDSHAKE" + " ntype=" + apeer.ntype
                    + " dist=" + apeer.distHigh + " remote=" + apeer);
        }
    }

    protected int recvChallenge() throws IOException {

        int challenge;

        try {
            final byte[] buf = read2BytePackage();
            @SuppressWarnings("resource")
            final OtpInputStream ibuf = new OtpInputStream(buf, 0);
            peer.ntype = ibuf.read1();
            if (peer.ntype != AbstractNode.NTYPE_R6) {
                throw new IOException("Unexpected peer type");
            }
            peer.distLow = peer.distHigh = ibuf.read2BE();
            peer.flags = ibuf.read4BE();
            challenge = ibuf.read4BE();
            final byte[] tmpname = new byte[buf.length - 11];
            ibuf.readN(tmpname);
            final String hisname = OtpErlangString.newString(tmpname);
            if (!hisname.equals(peer.node)) {
                throw new IOException(
                        "Handshake failed - peer has wrong name: " + hisname);
            }

            if ((peer.flags & AbstractNode.dFlagExtendedReferences) == 0) {
                throw new IOException(
                        "Handshake failed - peer cannot handle extended references");
            }

            if ((peer.flags & AbstractNode.dFlagExtendedPidsPorts) == 0) {
                throw new IOException(
                        "Handshake failed - peer cannot handle extended pids and ports");
            }

        } catch (final OtpErlangDecodeException e) {
            throw new IOException("Handshake failed - not enough data");
        }

        if (traceLevel >= handshakeThreshold) {
            System.out.println("<- " + "HANDSHAKE recvChallenge" + " from="
                    + peer.node + " challenge=" + challenge + " local="
                    + localNode);
        }

        return challenge;
    }

    protected void sendChallengeReply(final int challenge, final byte[] digest)
            throws IOException {

        @SuppressWarnings("resource")
        final OtpOutputStream obuf = new OtpOutputStream();
        obuf.write2BE(21);
        obuf.write1(ChallengeReply);
        obuf.write4BE(challenge);
        obuf.write(digest);
        obuf.writeToAndFlush(socket.getOutputStream());

        if (traceLevel >= handshakeThreshold) {
            System.out.println("-> " + "HANDSHAKE sendChallengeReply"
                    + " challenge=" + challenge + " digest=" + hex(digest)
                    + " local=" + localNode);
        }
    }

    // Would use Array.equals in newer JDK...
    private boolean digests_equals(final byte[] a, final byte[] b) {
        int i;
        for (i = 0; i < 16; ++i) {
            if (a[i] != b[i]) {
                return false;
            }
        }
        return true;
    }

    protected int recvChallengeReply(final int our_challenge)
            throws IOException, OtpAuthException {

        int challenge;
        final byte[] her_digest = new byte[16];

        try {
            final byte[] buf = read2BytePackage();
            @SuppressWarnings("resource")
            final OtpInputStream ibuf = new OtpInputStream(buf, 0);
            final int tag = ibuf.read1();
            if (tag != ChallengeReply) {
                throw new IOException("Handshake protocol error");
            }
            challenge = ibuf.read4BE();
            ibuf.readN(her_digest);
            final byte[] our_digest = genDigest(our_challenge,
                    localNode.cookie());
            if (!digests_equals(her_digest, our_digest)) {
                throw new OtpAuthException("Peer authentication error.");
            }
        } catch (final OtpErlangDecodeException e) {
            throw new IOException("Handshake failed - not enough data");
        }

        if (traceLevel >= handshakeThreshold) {
            System.out.println("<- " + "HANDSHAKE recvChallengeReply"
                    + " from=" + peer.node + " challenge=" + challenge
                    + " digest=" + hex(her_digest) + " local=" + localNode);
        }

        return challenge;
    }

    protected void sendChallengeAck(final byte[] digest) throws IOException {

        @SuppressWarnings("resource")
        final OtpOutputStream obuf = new OtpOutputStream();
        obuf.write2BE(17);
        obuf.write1(ChallengeAck);
        obuf.write(digest);

        obuf.writeToAndFlush(socket.getOutputStream());

        if (traceLevel >= handshakeThreshold) {
            System.out.println("-> " + "HANDSHAKE sendChallengeAck"
                    + " digest=" + hex(digest) + " local=" + localNode);
        }
    }

    protected void recvChallengeAck(final int our_challenge)
            throws IOException, OtpAuthException {

        final byte[] her_digest = new byte[16];
        try {
            final byte[] buf = read2BytePackage();
            @SuppressWarnings("resource")
            final OtpInputStream ibuf = new OtpInputStream(buf, 0);
            final int tag = ibuf.read1();
            if (tag != ChallengeAck) {
                throw new IOException("Handshake protocol error");
            }
            ibuf.readN(her_digest);
            final byte[] our_digest = genDigest(our_challenge,
                    localNode.cookie());
            if (!digests_equals(her_digest, our_digest)) {
                throw new OtpAuthException("Peer authentication error.");
            }
        } catch (final OtpErlangDecodeException e) {
            throw new IOException("Handshake failed - not enough data");
        } catch (final Exception e) {
            throw new OtpAuthException("Peer authentication error.");
        }

        if (traceLevel >= handshakeThreshold) {
            System.out.println("<- " + "HANDSHAKE recvChallengeAck" + " from="
                    + peer.node + " digest=" + hex(her_digest) + " local="
                    + localNode);
        }
    }

    protected void sendStatus(final String status) throws IOException {

        @SuppressWarnings("resource")
        final OtpOutputStream obuf = new OtpOutputStream();
        obuf.write2BE(status.length() + 1);
        obuf.write1(ChallengeStatus);
        obuf.write(status.getBytes());

        obuf.writeToAndFlush(socket.getOutputStream());

        if (traceLevel >= handshakeThreshold) {
            System.out.println("-> " + "HANDSHAKE sendStatus" + " status="
                    + status + " local=" + localNode);
        }
    }

    protected void recvStatus() throws IOException {

        try {
            final byte[] buf = read2BytePackage();
            @SuppressWarnings("resource")
            final OtpInputStream ibuf = new OtpInputStream(buf, 0);
            final int tag = ibuf.read1();
            if (tag != ChallengeStatus) {
                throw new IOException("Handshake protocol error");
            }
            final byte[] tmpbuf = new byte[buf.length - 1];
            ibuf.readN(tmpbuf);
            final String status = OtpErlangString.newString(tmpbuf);

            if (status.compareTo("ok") != 0) {
                throw new IOException("Peer replied with status '" + status
                        + "' instead of 'ok'");
            }
        } catch (final OtpErlangDecodeException e) {
            throw new IOException("Handshake failed - not enough data");
        }
        if (traceLevel >= handshakeThreshold) {
            System.out.println("<- " + "HANDSHAKE recvStatus (ok)" + " local="
                    + localNode);
        }
    }

    public void setFlags(final int flags) {
        this.flags = flags;
    }

    public int getFlags() {
        return flags;
    }
}


text:
<?php

require_once "jobs" . DIRECTORY_SEPARATOR . "ExportSpokeJson_Job_ExportItem.php";
require_once "jobs" . DIRECTORY_SEPARATOR . "ExportSpokeJson_Job_UnindexInterviews.php";
require_once "jobs" . DIRECTORY_SEPARATOR . "ExportSpokeJson_Job_UnindexItem.php";
require_once "models" . DIRECTORY_SEPARATOR . "Output" . DIRECTORY_SEPARATOR . "SpokeJson.php";
$pluginDir = dirname(dirname(__FILE__));
require_once $pluginDir . DIRECTORY_SEPARATOR . "RecursiveSuppression" . DIRECTORY_SEPARATOR . "models" . DIRECTORY_SEPARATOR . "SuppressionChecker.php";

class ExportSpokeJsonPlugin extends Omeka_Plugin_AbstractPlugin
{
    protected $_hooks = array(
        'admin_head',
        'admin_items_show_sidebar',
        'define_routes',
        'before_save_item',
    );

    public function hookBeforeSaveItem($args)
    {
        if (empty($args['post'])) {
            return;
        }

        $item = $args['record'];

        if (empty($item->id)) {
            return;
        }

        $suppressionField = false;
        switch($item->getItemType()->name) {
        case 'collections':
            $suppressionField = 'Collection Suppressed';
            break;
        case 'series':
            $suppressionField = 'Series Suppressed';
            break;
        case 'interviews':
            $suppressionField = 'Interview Suppressed';
            break;
        }

        if (!$suppressionField) {
            return;
        }

        $elementSet = get_record('ElementSet', array('name' => 'Item Type Metadata'));
        $element = false;
        foreach ($elementSet->getElements() as $elt) {
            if ($elt->name === $suppressionField) {
                $element = $elt;
                break;
            }
        }

        if (!$element) {
            return;
        }

        $id = $element->id;

        $itemSuppressionMetadata = json_decode(
            metadata($item, array('Item Type Metadata', $suppressionField), array('no_escape' => true, 'no_filter' => true)),
            true
        );

        $postSuppressionMetadata = json_decode(
            $args['post']['Elements'][$id][0]['text'],
            true
        );

        if (array_key_exists('recursive', $itemSuppressionMetadata)) {
            $recursiveInItem = $itemSuppressionMetadata['recursive'];
            $recursiveInPost = $postSuppressionMetadata['recursive'];

            # Should interviews in this item be suppressed?
            if (!$recursiveInItem && $recursiveInPost) {
                Zend_Registry::get('bootstrap')->getResource('jobs')->sendLongRunning(
                    'ExportSpokeJson_Job_UnindexInterviews', array(
                        'itemId' => $item['id'],
                    )
                );
            }
        }

        $suppressedInItem = $itemSuppressionMetadata['description'];
        $suppressedInPost = $postSuppressionMetadata['description'];

        # Has this specific item just been suppressed?
        if (!$suppressedInItem && $suppressedInPost) {
            Zend_Registry::get('bootstrap')->getResource('jobs')->sendLongRunning(
                'ExportSpokeJson_Job_UnindexItem', array(
                    'itemId' => $item['id'],
                    'recursive' => "1",
                )
            );
        }
    }

    public function hookAdminHead($args)
    {
        $request = Zend_Controller_Front::getInstance()->getRequest();

        $module = $request->getModuleName();
        if (is_null($module)) {
            $module = 'default';
        }
        $controller = $request->getControllerName();
        $action = $request->getActionName();

        if ($module === 'default'
            && $controller === 'items'
            && in_array($action, array('show')))
        {
            queue_js_file('export_json');
            queue_js_file('delete_json');
        }
    }

    public function hookAdminItemsShowSidebar($args)
    {
        $item = get_record_by_id('Item', $args['item']['id']);
        $checker = new SuppressionChecker($item);
        if ($checker->exportable()) {
            $itemType = $item->getItemType()->name;
            if ($itemType === 'interviews') {
                $visibleCheckbox = false;
            }
            else {
                $visibleCheckbox = true;
            }
            $exportable = true;
            $subitemCount = 0;
            # TODO: make this configurable
            if (false) {
                $subitemCount = $this->getSubitemCount($item);
                $exportable = $subitemCount <= 200;
            }
            echo get_view()->partial(
                'export-panel.php',
                array(
                    'visibleCheckbox' => $visibleCheckbox,
                    'subitemCount' => $subitemCount,
                    'exportable' => $exportable,
                )
            );
        }
    }

    public function hookDefineRoutes($args)
    {
        $args['router']->addRoute(
            'export_spoke_json_route',
            new Zend_Controller_Router_Route(
                'items/export/:id/:recursive',
                array(
                    'module' => 'export-spoke-json',
                    'controller' => 'items',
                    'action' => 'export'
                ),
                array(
                    'id' => '\d+',
                    'recursive' => '\d+',
                )
            )
        );
        $args['router']->addRoute(
            'unindex_spoke_json_route',
            new Zend_Controller_Router_Route(
                'items/unindex/:id/:recursive',
                array(
                    'module' => 'export-spoke-json',
                    'controller' => 'items',
                    'action' => 'unindex'
                ),
                array(
                    'id' => '\d+',
                    'recursive' => '\d+',
                )
            )
        );
    }

    private function getSubitemCount($item) {
        $count = 1;
        $objects = get_db()->getTable('ItemRelationsRelation')->findByObjectItemId($item->id);
        $objectRelations = array();
        foreach ($objects as $object) {
            if ($object->getPropertyText() !== "Is Part Of") {
                continue;
            }
            if (!($subitem = get_record_by_id('item', $object->subject_item_id))) {
                continue;
            }
            $count += $this->getSubitemCount($subitem);
        }
        return $count;
    }
}


text:
require 'rspec'

module Crabfarm
  module Utils
    module RSpecRunner
      extend self

      class SilentFormatter
        def initialize(_output)
          # do nothing with output (very silent!)
        end
      end

      def run_single_spec_for(_target, _tag=nil)
        setup_rspec_once

        begin
          configuration.reset

          runner = ::RSpec::Core::Runner.new config_options(_target)
          runner.setup $stderr, $stdout
          example = skip_all_but_one _tag
          runner.run_specs(world.ordered_example_groups)

          example
        ensure
          ::RSpec.clear_examples
        end
      end

    private

      def world
        ::RSpec.world
      end

      def configuration
        ::RSpec.configuration
      end

      def setup_rspec_once
        unless @ready
          ::RSpec::Core::Formatters.register SilentFormatter
          @ready = true
        end
      end

      def config_options(_target)
        ::RSpec::Core::ConfigurationOptions.new [
            _target,
            '-f','Crabfarm::Utils::RSpecRunner::SilentFormatter'
        ]
      end

      def skip_all_but_one(_tag)
        best_example = world.all_examples.inject(nil) do |best, example|
          example.metadata[:skip] = true
          if is_better_example? example, best, _tag
            example
          else
            best
          end
        end

        best_example.metadata[:skip] = false if best_example
        best_example
      end

      def is_better_example?(_new, _old, _tag)
        return true if _old.nil?

        if _tag
          new_tagged = !!(_new.metadata[_tag])
          old_tagged = !!(_old.metadata[_tag])

          # preffer tagged
          return new_tagged if new_tagged != old_tagged
        end

        # preffer higher line number
        return _new.metadata[:line_number] > _old.metadata[:line_number]
      end

    end
  end
end


text:
package org.powlab.jeye.tests.assign;

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

public class AssignTest5 {

    public void test() {
        List l = new ArrayList();
        l = new LinkedList();
        l.size();
    }
}