text:
package org.tensorflow.framework;

public final class GraphTransferInfoProto {
  private GraphTransferInfoProto() {}
  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistryLite registry) {
  }

  public static void registerAllExtensions(
      com.google.protobuf.ExtensionRegistry registry) {
    registerAllExtensions(
        (com.google.protobuf.ExtensionRegistryLite) registry);
  }
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_tensorflow_GraphTransferInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_tensorflow_GraphTransferInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_tensorflow_GraphTransferInfo_NodeInput_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_tensorflow_GraphTransferInfo_NodeInput_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_tensorflow_GraphTransferInfo_NodeInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_tensorflow_GraphTransferInfo_NodeInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_tensorflow_GraphTransferInfo_ConstNodeInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_tensorflow_GraphTransferInfo_ConstNodeInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_tensorflow_GraphTransferInfo_NodeInputInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_tensorflow_GraphTransferInfo_NodeInputInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_tensorflow_GraphTransferInfo_NodeOutputInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_tensorflow_GraphTransferInfo_NodeOutputInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_tensorflow_GraphTransferInfo_GraphInputNodeInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_tensorflow_GraphTransferInfo_GraphInputNodeInfo_fieldAccessorTable;
  static final com.google.protobuf.Descriptors.Descriptor
    internal_static_tensorflow_GraphTransferInfo_GraphOutputNodeInfo_descriptor;
  static final
    com.google.protobuf.GeneratedMessageV3.FieldAccessorTable
      internal_static_tensorflow_GraphTransferInfo_GraphOutputNodeInfo_fieldAccessorTable;

  public static com.google.protobuf.Descriptors.FileDescriptor
      getDescriptor() {
    return descriptor;
  }
  private static  com.google.protobuf.Descriptors.FileDescriptor
      descriptor;
  static {
    java.lang.String[] descriptorData = {
      "\n3tensorflow/core/framework/graph_transf" +
      "er_info.proto\022\ntensorflow\032%tensorflow/co" +
      "re/framework/types.proto\"\253\t\n\021GraphTransf" +
      "erInfo\0229\n\tnode_info\030\001 \003(\0132&.tensorflow.G" +
      "raphTransferInfo.NodeInfo\022D\n\017const_node_" +
      "info\030\002 \003(\0132+.tensorflow.GraphTransferInf" +
      "o.ConstNodeInfo\022D\n\017node_input_info\030\003 \003(\013" +
      "2+.tensorflow.GraphTransferInfo.NodeInpu" +
      "tInfo\022F\n\020node_output_info\030\004 \003(\0132,.tensor" +
      "flow.GraphTransferInfo.NodeOutputInfo\022O\n",
      "\025graph_input_node_info\030\005 \003(\01320.tensorflo" +
      "w.GraphTransferInfo.GraphInputNodeInfo\022Q" +
      "\n\026graph_output_node_info\030\006 \003(\01321.tensorf" +
      "low.GraphTransferInfo.GraphOutputNodeInf" +
      "o\022>\n\013destination\030\007 \001(\0162).tensorflow.Grap" +
      "hTransferInfo.Destination\0321\n\tNodeInput\022\017" +
      "\n\007node_id\030\001 \001(\005\022\023\n\013output_port\030\002 \001(\005\032\216\001\n" +
      "\010NodeInfo\022\014\n\004name\030\001 \001(\t\022\017\n\007node_id\030\002 \001(\005" +
      "\022\021\n\ttype_name\030\003 \001(\t\022\021\n\tsoc_op_id\030\004 \001(\005\022\022" +
      "\n\npadding_id\030\005 \001(\005\022\023\n\013input_count\030\006 \001(\005\022",
      "\024\n\014output_count\030\007 \001(\005\032p\n\rConstNodeInfo\022\014" +
      "\n\004name\030\001 \001(\t\022\017\n\007node_id\030\002 \001(\005\022\r\n\005shape\030\003" +
      " \003(\003\022\014\n\004data\030\004 \001(\014\022#\n\005dtype\030\005 \001(\0162\024.tens" +
      "orflow.DataType\032]\n\rNodeInputInfo\022\017\n\007node" +
      "_id\030\001 \001(\005\022;\n\nnode_input\030\002 \003(\0132\'.tensorfl" +
      "ow.GraphTransferInfo.NodeInput\0328\n\016NodeOu" +
      "tputInfo\022\017\n\007node_id\030\001 \001(\005\022\025\n\rmax_byte_si" +
      "ze\030\002 \003(\005\032V\n\022GraphInputNodeInfo\022\014\n\004name\030\001" +
      " \001(\t\022\r\n\005shape\030\002 \003(\003\022#\n\005dtype\030\003 \001(\0162\024.ten" +
      "sorflow.DataType\032W\n\023GraphOutputNodeInfo\022",
      "\014\n\004name\030\001 \001(\t\022\r\n\005shape\030\002 \003(\003\022#\n\005dtype\030\003 " +
      "\001(\0162\024.tensorflow.DataType\"#\n\013Destination" +
      "\022\007\n\003NOP\020\000\022\013\n\007HEXAGON\020\001B7\n\030org.tensorflow" +
      ".frameworkB\026GraphTransferInfoProtoP\001\370\001\001b" +
      "\006proto3"
    };
    com.google.protobuf.Descriptors.FileDescriptor.InternalDescriptorAssigner assigner =
        new com.google.protobuf.Descriptors.FileDescriptor.    InternalDescriptorAssigner() {
          public com.google.protobuf.ExtensionRegistry assignDescriptors(
              com.google.protobuf.Descriptors.FileDescriptor root) {
            descriptor = root;
            return null;
          }
        };
    com.google.protobuf.Descriptors.FileDescriptor
      .internalBuildGeneratedFileFrom(descriptorData,
        new com.google.protobuf.Descriptors.FileDescriptor[] {
          org.tensorflow.framework.TypesProtos.getDescriptor(),
        }, assigner);
    internal_static_tensorflow_GraphTransferInfo_descriptor =
      getDescriptor().getMessageTypes().get(0);
    internal_static_tensorflow_GraphTransferInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_tensorflow_GraphTransferInfo_descriptor,
        new java.lang.String[] { "NodeInfo", "ConstNodeInfo", "NodeInputInfo", "NodeOutputInfo", "GraphInputNodeInfo", "GraphOutputNodeInfo", "Destination", });
    internal_static_tensorflow_GraphTransferInfo_NodeInput_descriptor =
      internal_static_tensorflow_GraphTransferInfo_descriptor.getNestedTypes().get(0);
    internal_static_tensorflow_GraphTransferInfo_NodeInput_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_tensorflow_GraphTransferInfo_NodeInput_descriptor,
        new java.lang.String[] { "NodeId", "OutputPort", });
    internal_static_tensorflow_GraphTransferInfo_NodeInfo_descriptor =
      internal_static_tensorflow_GraphTransferInfo_descriptor.getNestedTypes().get(1);
    internal_static_tensorflow_GraphTransferInfo_NodeInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_tensorflow_GraphTransferInfo_NodeInfo_descriptor,
        new java.lang.String[] { "Name", "NodeId", "TypeName", "SocOpId", "PaddingId", "InputCount", "OutputCount", });
    internal_static_tensorflow_GraphTransferInfo_ConstNodeInfo_descriptor =
      internal_static_tensorflow_GraphTransferInfo_descriptor.getNestedTypes().get(2);
    internal_static_tensorflow_GraphTransferInfo_ConstNodeInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_tensorflow_GraphTransferInfo_ConstNodeInfo_descriptor,
        new java.lang.String[] { "Name", "NodeId", "Shape", "Data", "Dtype", });
    internal_static_tensorflow_GraphTransferInfo_NodeInputInfo_descriptor =
      internal_static_tensorflow_GraphTransferInfo_descriptor.getNestedTypes().get(3);
    internal_static_tensorflow_GraphTransferInfo_NodeInputInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_tensorflow_GraphTransferInfo_NodeInputInfo_descriptor,
        new java.lang.String[] { "NodeId", "NodeInput", });
    internal_static_tensorflow_GraphTransferInfo_NodeOutputInfo_descriptor =
      internal_static_tensorflow_GraphTransferInfo_descriptor.getNestedTypes().get(4);
    internal_static_tensorflow_GraphTransferInfo_NodeOutputInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_tensorflow_GraphTransferInfo_NodeOutputInfo_descriptor,
        new java.lang.String[] { "NodeId", "MaxByteSize", });
    internal_static_tensorflow_GraphTransferInfo_GraphInputNodeInfo_descriptor =
      internal_static_tensorflow_GraphTransferInfo_descriptor.getNestedTypes().get(5);
    internal_static_tensorflow_GraphTransferInfo_GraphInputNodeInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_tensorflow_GraphTransferInfo_GraphInputNodeInfo_descriptor,
        new java.lang.String[] { "Name", "Shape", "Dtype", });
    internal_static_tensorflow_GraphTransferInfo_GraphOutputNodeInfo_descriptor =
      internal_static_tensorflow_GraphTransferInfo_descriptor.getNestedTypes().get(6);
    internal_static_tensorflow_GraphTransferInfo_GraphOutputNodeInfo_fieldAccessorTable = new
      com.google.protobuf.GeneratedMessageV3.FieldAccessorTable(
        internal_static_tensorflow_GraphTransferInfo_GraphOutputNodeInfo_descriptor,
        new java.lang.String[] { "Name", "Shape", "Dtype", });
    org.tensorflow.framework.TypesProtos.getDescriptor();
  }

  // @@protoc_insertion_point(outer_class_scope)
}


text:
class Section
  class SearchReference < ::SearchReference
    collection_path "sections/:referenced_id/search_references"
  end
end

redpajama_set_name: RedPajamaGithub


text:
import numpy as np

from bokeh.models import ColumnDataSource, Plot, LinearAxis, Grid
from bokeh.models.markers import Cross
from bokeh.io import curdoc, show

N = 9
x = np.linspace(-2, 2, N)
y = x**2
sizes = np.linspace(10, 20, N)

source = ColumnDataSource(dict(x=x, y=y, sizes=sizes))

plot = Plot(
    title=None, plot_width=300, plot_height=300,
    h_symmetry=False, v_symmetry=False, min_border=0, toolbar_location=None)

glyph = Cross(x="x", y="y", size="sizes", line_color="#e6550d", fill_color=None, line_width=2)
plot.add_glyph(source, glyph)

xaxis = LinearAxis()
plot.add_layout(xaxis, 'below')

yaxis = LinearAxis()
plot.add_layout(yaxis, 'left')

plot.add_layout(Grid(dimension=0, ticker=xaxis.ticker))
plot.add_layout(Grid(dimension=1, ticker=yaxis.ticker))

curdoc().add_root(plot)

show(plot)


text:
using System;
using JetBrains.Annotations;

namespace JsonApiDotNetCoreTests.IntegrationTests.Microservices.Messages
{
    [UsedImplicitly(ImplicitUseTargetFlags.Members)]
    public sealed class UserAddedToGroupContent : IMessageContent
    {
        public int FormatVersion => 1;

        public Guid UserId { get; set; }
        public Guid GroupId { get; set; }
    }
}


text:
FROM debian:wheezy

# Author: MobileSnapp Inc.
MAINTAINER MobileSnapp <support@mobilesnapp.com>

# Install beanstalkd
ADD install.sh install.sh
RUN chmod +x install.sh && ./install.sh && rm install.sh

# Expose port
EXPOSE 11300

CMD ["beanstalkd", "-p", "11300"]


text:
package com.vmware.vim25;

/**
* @author Steve Jin (http://www.doublecloud.org)
* @version 5.1
*/

@SuppressWarnings("all")
public class VirtualMachineIdeDiskDeviceInfo extends VirtualMachineDiskDeviceInfo {
  public VirtualMachineIdeDiskDevicePartitionInfo[] partitionTable;

  public VirtualMachineIdeDiskDevicePartitionInfo[] getPartitionTable() {
    return this.partitionTable;
  }

  public void setPartitionTable(VirtualMachineIdeDiskDevicePartitionInfo[] partitionTable) {
    this.partitionTable=partitionTable;
  }
}


text:
var io = require('socket.io-client');

var generateRandomString = function(length, includeLetters, includeNumbers){
    var dict = "";
    if (includeLetters)
        dict += "abcdefghjklmnpqrstuvwxyz";
    if (includeNumbers)
        dict += "123456789";
    var str = 'x'.repeat(length).replace(/[xy]/g, function(c) {
        var r = Math.random()*dict.length;
        return dict.charAt(r);
    });

    return str;
};

var generateUserId = function() {
    return generateRandomString(32, true, true);
};

var testClient = function(sessionId, username) {

    var model = {
        uid: generateUserId(),
        sid: sessionId,
        qrcodeUrl: '',
        showSettings: false,
        showConnectCode: false,
        newUsername: '',
        connected: false,
        loggedIn: false,
        roomType: 'unknown',
        transport: 'unknown',
        username: username,
        isLoggedIn: function () {
            return this.username && this.username.length > 0;
        },
        vote: null
    };

    var log = function(msg) {
        console.log(model.username + "> " + msg);
    };

    log("uid: " + model.uid);

    log('connecting');
    var socket = io('http://localhost:4000');

    socket.on('connect', function () {
        log('connect');
        model.connected = true;
        //model.transport = socket.transport();
        doJoin();
    });

    var doJoin = function() {
        if (model.connected && model.username) {
            socket.emit('bindUser', {sid: model.sid, uid: model.uid, username: model.username});
        }
    };

    socket.on('disconnect', function () {
        log('disconnect');
        model.connected = false;
        model.loggedIn = false;
    });

    socket.on('failure', function(reason) {
        model.connected = false;
        model.loggedIn = false;
        log(reason);
    });

    socket.on('loggedIn', function() {
        log('loggedIn');
        model.loggedIn = true;
    });

    socket.on('roomUpdate', function(room) {
        log('roomUpdate');
        model.roomType = room.roomType;
    });

    socket.on('reset', function(mode) {
        log('reset');
        model.vote = null;

        setTimeout(function() {
            log('voting...');
            var choices = new Array(1, 2,2,2, 3,3,3,3,3, 5,5,5,5, 8, 13, 20, 40, 100);
            //var choices = new Array(-5, -5, -3, -3, -3, -3, -3, -3 -1, -1,-1, 0, +1, +3, +5);
            model.vote = choices[ Math.floor(Math.random()*choices.length)];
            socket.emit('vote', model.vote);
        }, (Math.random() * 3000) + 1500);
    });

    return {
        leave: function() {
            log("leave");
            socket.emit("leave");
        }
    };
};

function getSillyName() {
    var firstName = ["Runny", "Buttercup", "Dinky", "Stinky", "Crusty",
        "Greasy", "Gidget", "Cheesypoof", "Lumpy", "Wacky", "Tiny", "Flunky",
        "Fluffy", "Zippy", "Doofus", "Gobsmacked", "Slimy", "Grimy", "Salamander",
        "Oily", "Burrito", "Bumpy", "Loopy", "Snotty", "Irving", "Egbert"];

    var lastName1 = ["Snicker", "Buffalo", "Gross", "Bubble", "Sheep",
        "Corset", "Toilet", "Lizard", "Waffle", "Kumquat", "Burger", "Chimp", "Liver",
        "Gorilla", "Rhino", "Emu", "Pizza", "Toad", "Gerbil", "Pickle", "Tofu",
        "Chicken", "Potato", "Hamster", "Lemur", "Vermin"];

    var name = firstName[ Math.floor(Math.random()*firstName.length)] + " " + lastName1[ Math.floor(Math.random()*lastName1.length)];
    return name;
}

var clients = [];
var nextIndex = 0;
var startNextClient = function() {
    clients.push(testClient('721458', getSillyName()));
    nextIndex++;
    if (nextIndex < 100)
        setTimeout(startNextClient, 1);
};
startNextClient();

var closeNextClient = function() {
    if (clients.length > 0) {
        clients.shift().leave();
        setTimeout(closeNextClient, 1);
    }
};

var stdin = process.openStdin();
stdin.on("data", function(text) {
    console.log("Shutting down....");
    closeNextClient();
});


text:
class Cancannible::Preloader
  def self.preload_abilities!(grantee, cancan_ability_object)
    new(grantee, cancan_ability_object).preload!
  end

  attr_accessor :grantee
  attr_accessor :cancan_ability_object

  def initialize(grantee, cancan_ability_object)
    self.grantee = grantee
    self.cancan_ability_object = cancan_ability_object
  end

  def preload!
    return unless grantee.respond_to?(:inherited_permissions)

    # load inherited permissions to CanCan Abilities
    preload_abilities_from_permissions(grantee.inherited_permissions)
    # load user-based permissions from database to CanCan Abilities
    preload_abilities_from_permissions(grantee.permissions.reload)
    # return the ability object
    cancan_ability_object
  end

  def preload_abilities_from_permissions(perms)
    perms.each do |permission|
      ability = permission.ability.to_sym
      action = permission.asserted ? :can : :cannot

      resource_type,model_resource = resolve_resource_type(permission.resource_type)

      if !resource_type || resource_type.is_a?(Symbol)
        # nil or symbolic resource types: apply generic unrestricted permission to the resource_type
        cancan_ability_object.send( action,  ability, resource_type )
        next
      else
        # model-based resource types: skip if we cannot get a model instance
        next unless model_resource
      end

      if permission.resource_id.nil?
        if action == :cannot
          # apply generic unrestricted permission to the class
          cancan_ability_object.send(action, ability, resource_type)
        else
          refinements = resolve_resource_refinements(ability,model_resource)

          if refinements.empty?
            # apply generic unrestricted permission to the class
            cancan_ability_object.send(action, ability, resource_type)
          else
            secondary_refinements = resolve_resource_refinements(ability,model_resource,2).presence || [{}]
            refinements.each do |refinement|
              secondary_refinements.each do |secondary_refinement|
                cancan_ability_object.send( action,  ability, resource_type, refinement.merge(secondary_refinement))
              end
            end
          end
        end
      elsif resource_type.find_by_id(permission.resource_id)
        cancan_ability_object.send( action,  ability, resource_type, id: permission.resource_id)
      end
    end
  end

  def resolve_resource_type(given_resource_type)
    model_resource = nil
    resource_type = given_resource_type
    resource_type = resource_type == resource_type.downcase ? resource_type.to_sym : resource_type.constantize rescue nil
    model_resource = resource_type.respond_to?(:new) ? resource_type.new : resource_type rescue nil
    [resource_type,model_resource]
  end

  def resolve_resource_refinements(ability, model_resource, stage=1)
    Array(Cancannible.refinements[stage-1]).each_with_object([]) do |refinement,memo|
      refinement_attributes = refinement.dup

      allow_nil = !!(refinement_attributes.delete(:allow_nil))

      refinement_if_condition = refinement_attributes.delete(:if)
      next if refinement_if_condition.respond_to?(:call) && !refinement_if_condition.call(grantee,model_resource)

      refinement_scope = Array(refinement_attributes.delete(:scope))
      next if refinement_scope.present? &&  !refinement_scope.include?(ability)

      refinement_except = Array(refinement_attributes.delete(:except))
      next if refinement_except.present? &&  refinement_except.include?(ability)

      refinement_attribute_names = refinement_attributes.keys.map{|k| "#{k}" }
      next unless (refinement_attribute_names - model_resource.attribute_names).empty?

      restriction = {}
      refinement_attributes.each do |key,value|
        if value.is_a?(Symbol)
          if grantee.respond_to?(value)
            restriction[key] = if allow_nil
              Array(grantee.send(value)) + [nil]
            else
              grantee.send(value)
            end
          end
        else
          restriction[key] = value
        end
      end
      memo.push(restriction) if restriction.present?
    end
  end
end


text:
package org.apache.hive.service.cli.operation;

import java.io.File;
import java.io.FileNotFoundException;
import java.util.EnumSet;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

import org.apache.hadoop.hive.conf.HiveConf;
import org.apache.hadoop.hive.ql.QueryState;
import org.apache.hadoop.hive.ql.processors.CommandProcessorResponse;
import org.apache.hadoop.hive.ql.session.OperationLog;
import org.apache.hive.service.cli.FetchOrientation;
import org.apache.hive.service.cli.HiveSQLException;
import org.apache.hive.service.cli.OperationHandle;
import org.apache.hive.service.cli.OperationState;
import org.apache.hive.service.cli.OperationStatus;
import org.apache.hive.service.cli.OperationType;
import org.apache.hive.service.cli.RowSet;
import org.apache.hive.service.cli.TableSchema;
import org.apache.hive.service.cli.session.HiveSession;
import org.apache.hive.service.rpc.thrift.TProtocolVersion;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public abstract class Operation {
  protected final HiveSession parentSession;
  private OperationState state = OperationState.INITIALIZED;
  private final OperationHandle opHandle;
  private HiveConf configuration;
  public static final Logger LOG = LoggerFactory.getLogger(Operation.class.getName());
  public static final FetchOrientation DEFAULT_FETCH_ORIENTATION = FetchOrientation.FETCH_NEXT;
  public static final long DEFAULT_FETCH_MAX_ROWS = 100;
  protected boolean hasResultSet;
  protected volatile HiveSQLException operationException;
  protected final boolean runAsync;
  protected volatile Future<?> backgroundHandle;
  protected OperationLog operationLog;
  protected boolean isOperationLogEnabled;
  protected Map<String, String> confOverlay = new HashMap<String, String>();

  private long operationTimeout;
  private long lastAccessTime;

  protected final QueryState queryState;

  protected static final EnumSet<FetchOrientation> DEFAULT_FETCH_ORIENTATION_SET =
      EnumSet.of(FetchOrientation.FETCH_NEXT,FetchOrientation.FETCH_FIRST);

  protected Operation(HiveSession parentSession, OperationType opType) {
    this(parentSession, null, opType);
  }

  protected Operation(HiveSession parentSession, Map<String, String> confOverlay,
      OperationType opType) {
    this(parentSession, confOverlay, opType, false);
  }

  protected Operation(HiveSession parentSession,
      Map<String, String> confOverlay, OperationType opType, boolean runInBackground) {
    this.parentSession = parentSession;
    this.confOverlay = confOverlay;
    this.runAsync = runInBackground;
    this.opHandle = new OperationHandle(opType, parentSession.getProtocolVersion());
    lastAccessTime = System.currentTimeMillis();
    operationTimeout = HiveConf.getTimeVar(parentSession.getHiveConf(),
        HiveConf.ConfVars.HIVE_SERVER2_IDLE_OPERATION_TIMEOUT, TimeUnit.MILLISECONDS);
    queryState = new QueryState(parentSession.getHiveConf(), confOverlay, runInBackground);
  }

  public Future<?> getBackgroundHandle() {
    return backgroundHandle;
  }

  protected void setBackgroundHandle(Future<?> backgroundHandle) {
    this.backgroundHandle = backgroundHandle;
  }

  public boolean shouldRunAsync() {
    return runAsync;
  }

  public void setConfiguration(HiveConf configuration) {
    this.configuration = new HiveConf(configuration);
  }

  public HiveConf getConfiguration() {
    return new HiveConf(configuration);
  }

  public HiveSession getParentSession() {
    return parentSession;
  }

  public OperationHandle getHandle() {
    return opHandle;
  }

  public TProtocolVersion getProtocolVersion() {
    return opHandle.getProtocolVersion();
  }

  public OperationType getType() {
    return opHandle.getOperationType();
  }

  public OperationStatus getStatus() {
    return new OperationStatus(state, operationException);
  }

  public boolean hasResultSet() {
    return hasResultSet;
  }

  protected void setHasResultSet(boolean hasResultSet) {
    this.hasResultSet = hasResultSet;
    opHandle.setHasResultSet(hasResultSet);
  }

  public OperationLog getOperationLog() {
    return operationLog;
  }

  protected final OperationState setState(OperationState newState) throws HiveSQLException {
    state.validateTransition(newState);
    this.state = newState;
    this.lastAccessTime = System.currentTimeMillis();
    return this.state;
  }

  public boolean isTimedOut(long current) {
    if (operationTimeout == 0) {
      return false;
    }
    if (operationTimeout > 0) {
      // check only when it's in terminal state
      return state.isTerminal() && lastAccessTime + operationTimeout <= current;
    }
    return lastAccessTime + -operationTimeout <= current;
  }

  public long getLastAccessTime() {
    return lastAccessTime;
  }

  public long getOperationTimeout() {
    return operationTimeout;
  }

  public void setOperationTimeout(long operationTimeout) {
    this.operationTimeout = operationTimeout;
  }

  protected void setOperationException(HiveSQLException operationException) {
    this.operationException = operationException;
  }

  protected final void assertState(OperationState state) throws HiveSQLException {
    if (this.state != state) {
      throw new HiveSQLException("Expected state " + state + ", but found " + this.state);
    }
    this.lastAccessTime = System.currentTimeMillis();
  }

  public boolean isRunning() {
    return OperationState.RUNNING.equals(state);
  }

  public boolean isFinished() {
    return OperationState.FINISHED.equals(state);
  }

  public boolean isCanceled() {
    return OperationState.CANCELED.equals(state);
  }

  public boolean isFailed() {
    return OperationState.ERROR.equals(state);
  }

  protected void createOperationLog() {
    if (parentSession.isOperationLogEnabled()) {
      File operationLogFile = new File(parentSession.getOperationLogSessionDir(),
          opHandle.getHandleIdentifier().toString());
      isOperationLogEnabled = true;

      // create log file
      try {
        if (operationLogFile.exists()) {
          LOG.warn("The operation log file should not exist, but it is already there: " +
              operationLogFile.getAbsolutePath());
          operationLogFile.delete();
        }
        if (!operationLogFile.createNewFile()) {
          // the log file already exists and cannot be deleted.
          // If it can be read/written, keep its contents and use it.
          if (!operationLogFile.canRead() || !operationLogFile.canWrite()) {
            LOG.warn("The already existed operation log file cannot be recreated, " +
                "and it cannot be read or written: " + operationLogFile.getAbsolutePath());
            isOperationLogEnabled = false;
            return;
          }
        }
      } catch (Exception e) {
        LOG.warn("Unable to create operation log file: " + operationLogFile.getAbsolutePath(), e);
        isOperationLogEnabled = false;
        return;
      }

      // create OperationLog object with above log file
      try {
        operationLog = new OperationLog(opHandle.toString(), operationLogFile, parentSession.getHiveConf());
      } catch (FileNotFoundException e) {
        LOG.warn("Unable to instantiate OperationLog object for operation: " +
            opHandle, e);
        isOperationLogEnabled = false;
        return;
      }

      // register this operationLog to current thread
      OperationLog.setCurrentOperationLog(operationLog);
    }
  }

  protected void unregisterOperationLog() {
    if (isOperationLogEnabled) {
      OperationLog.removeCurrentOperationLog();
    }
  }

  /**
   * Invoked before runInternal().
   * Set up some preconditions, or configurations.
   */
  protected void beforeRun() {
    createOperationLog();
  }

  /**
   * Invoked after runInternal(), even if an exception is thrown in runInternal().
   * Clean up resources, which was set up in beforeRun().
   */
  protected void afterRun() {
    unregisterOperationLog();
  }

  /**
   * Implemented by subclass of Operation class to execute specific behaviors.
   * @throws HiveSQLException
   */
  protected abstract void runInternal() throws HiveSQLException;

  public void run() throws HiveSQLException {
    beforeRun();
    try {
      runInternal();
    } finally {
      afterRun();
    }
  }

  protected void cleanupOperationLog() {
    if (isOperationLogEnabled) {
      if (operationLog == null) {
        LOG.error("Operation [ " + opHandle.getHandleIdentifier() + " ] "
          + "logging is enabled, but its OperationLog object cannot be found.");
      } else {
        operationLog.close();
      }
    }
  }

  // TODO: make this abstract and implement in subclasses.
  public void cancel() throws HiveSQLException {
    setState(OperationState.CANCELED);
    throw new UnsupportedOperationException("SQLOperation.cancel()");
  }

  public abstract void close() throws HiveSQLException;

  public abstract TableSchema getResultSetSchema() throws HiveSQLException;

  public abstract RowSet getNextRowSet(FetchOrientation orientation, long maxRows) throws HiveSQLException;

  public RowSet getNextRowSet() throws HiveSQLException {
    return getNextRowSet(FetchOrientation.FETCH_NEXT, DEFAULT_FETCH_MAX_ROWS);
  }

  /**
   * Verify if the given fetch orientation is part of the default orientation types.
   * @param orientation
   * @throws HiveSQLException
   */
  protected void validateDefaultFetchOrientation(FetchOrientation orientation)
      throws HiveSQLException {
    validateFetchOrientation(orientation, DEFAULT_FETCH_ORIENTATION_SET);
  }

  /**
   * Verify if the given fetch orientation is part of the supported orientation types.
   * @param orientation
   * @param supportedOrientations
   * @throws HiveSQLException
   */
  protected void validateFetchOrientation(FetchOrientation orientation,
      EnumSet<FetchOrientation> supportedOrientations) throws HiveSQLException {
    if (!supportedOrientations.contains(orientation)) {
      throw new HiveSQLException("The fetch type " + orientation.toString() +
          " is not supported for this resultset", "HY106");
    }
  }

  protected HiveSQLException toSQLException(String prefix, CommandProcessorResponse response) {
    HiveSQLException ex = new HiveSQLException(prefix + ": " + response.getErrorMessage(),
        response.getSQLState(), response.getResponseCode());
    if (response.getException() != null) {
      ex.initCause(response.getException());
    }
    return ex;
  }

  protected Map<String, String> getConfOverlay() {
    return confOverlay;
  }
}


text:
$toolsDir = Split-Path $MyInvocation.MyCommand.Definition
$is64     = (Get-OSArchitectureWidth 64) -and $env:chocolateyForceX86 -ne 'true'

$packageArgs = @{
    packageName   = 'krita'
    fileType      = 'exe'
    silentArgs    = "/S"
    softwareName  = 'Krita'

    url           = 'https://download.kde.org/stable/krita/4.4.1/krita-x86-4.4.1-setup.exe'
    checksum      = 'CDE368CD4983293E18E92826A4A7EF40CD1CC39B07E18AE545345474A48982F0'
    checksumType  = 'sha256'
    file64        = Get-Item $toolsDir\*.exe
}

# https://github.com/chocolatey-community/chocolatey-coreteampackages/issues/1289#issuecomment-498815481
if ($is64) {
    $packageArgs.Remove('url');
    $packageArgs.Remove('checksum')
    $packageArgs.Remove('checksumType')
    Install-ChocolateyInstallPackage @packageArgs
} else {
    $packageArgs.Remove('file64')
    Install-ChocolateyPackage @packageArgs
}

Get-ChildItem $toolsDir\*.exe | ForEach-Object { Remove-Item $_ -ea 0; if (Test-Path $_) { Set-Content -Value "" -Path "$_.ignore" }}


text:
package org.easycloud.las.analyzer.recommender.item;

import org.apache.hadoop.io.Text;
import org.apache.hadoop.mrunit.MapDriver;
import org.apache.hadoop.mrunit.MapReduceDriver;
import org.apache.hadoop.mrunit.ReduceDriver;
import org.easycloud.las.analyzer.recommender.VectorWritable;
import org.easycloud.las.analyzer.util.RandomAccessVector;
import org.junit.Before;
import org.junit.Test;

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

import static org.easycloud.las.analyzer.Constants.HOUSE_TYPE_RENT;
import static org.easycloud.las.analyzer.Constants.HOUSE_TYPE_SELL;

/**
 * Created with IntelliJ IDEA.
 * User: ibntab
 * Date: 13-7-30
 * Time: 上午11:41
 */
public class UserVectorToCooccurrenceTests {

    private MapDriver<Text, VectorWritable, Text, Text> mapDriver;
    private ReduceDriver<Text, Text, Text, VectorWritable> reduceDriver;

    private MapReduceDriver<Text, VectorWritable, Text, Text, Text, VectorWritable> mapReduceDriver;

    private String userCode1, userCode2;
    private String houseCode1, houseCode2, houseCode3;
    private byte houseType1, houseType2, houseType3;

    @Before
    public void setUp() throws Exception {
        UserVectorToCooccurrenceMapper mapper = new UserVectorToCooccurrenceMapper();
        mapDriver = MapDriver.newMapDriver(mapper);

        UserVectorToCooccurrenceReducer reducer = new UserVectorToCooccurrenceReducer();
        reduceDriver = ReduceDriver.newReduceDriver(reducer);

        mapReduceDriver = MapReduceDriver.newMapReduceDriver(mapper, reducer);

        userCode1 = "6e2b58d1ed29f167976f9c88c835951d";
        userCode2 = "21a5a5dcde0ee2805d781591e5cc2e79";

        houseCode1 = "BJFT85558816";
        houseType1 = HOUSE_TYPE_SELL;

        houseCode2 = "BJCP85062036";
        houseType2 = HOUSE_TYPE_RENT;

        houseCode3 = "BJFT84662905";
        houseType3 = HOUSE_TYPE_RENT;
    }

    @Test
    public void testMapper() throws Exception {
        RandomAccessVector<String> userVector = new RandomAccessVector<String>(2);
        String house1 = houseCode1 + "/" + houseType1;
        String house3 = houseCode3 + "/" + houseType3;
        userVector.set(house1, 1);
        userVector.set(house3, 1);
        mapDriver.withInput(new Text(userCode1), new VectorWritable(userVector));
        mapDriver.addOutput(new Text(house1), new Text(house1));
        mapDriver.addOutput(new Text(house1), new Text(house3));
        mapDriver.addOutput(new Text(house3), new Text(house1));
        mapDriver.addOutput(new Text(house3), new Text(house3));

        mapDriver.runTest(false);
    }

    @Test
    public void testReducer() throws Exception {
        List<Text> inputValue = new ArrayList<Text>();
        String house1 = houseCode1 + "/" + houseType1;
        String house3 = houseCode3 + "/" + houseType3;
        inputValue.add(new Text(house1));
        inputValue.add(new Text(house3));
        inputValue.add(new Text(house3));
        reduceDriver.withInput(new Text(house1), inputValue);
        RandomAccessVector<String> outputValue = new RandomAccessVector<String>(2);
        outputValue.set(house1, 1);
        outputValue.set(house3, 2);
        reduceDriver.withOutput(new Text(house1), new VectorWritable(outputValue));

        reduceDriver.runTest();
    }

    @Test
    public void testMapReduce() throws Exception {

        String house1 = houseCode1 + "/" + houseType1;
        String house2 = houseCode2 + "/" + houseType2;
        String house3 = houseCode3 + "/" + houseType3;

        RandomAccessVector<String> userVector1 = new RandomAccessVector<String>(3);
        userVector1.set(house1, 1);
        userVector1.set(house2, 1);
        userVector1.set(house3, 1);

        RandomAccessVector<String> userVector2 = new RandomAccessVector<String>(1);
        userVector2.set(house2, 1);
        userVector2.set(house3, 1);

        mapReduceDriver.addInput(new Text(userCode1), new VectorWritable(userVector1));
        mapReduceDriver.addInput(new Text(userCode2), new VectorWritable(userVector2));

        RandomAccessVector<String> cooccurrenceRow1 = new RandomAccessVector<String>();
        cooccurrenceRow1.set(house1, 1);
        cooccurrenceRow1.set(house2, 1);
        cooccurrenceRow1.set(house3, 1);

        RandomAccessVector<String> cooccurrenceRow2 = new RandomAccessVector<String>();
        cooccurrenceRow2.set(house1, 1);
        cooccurrenceRow2.set(house2, 2);
        cooccurrenceRow2.set(house3, 2);

        RandomAccessVector<String> cooccurrenceRow3 = new RandomAccessVector<String>();
        cooccurrenceRow3.set(house1, 1);
        cooccurrenceRow3.set(house2, 2);
        cooccurrenceRow3.set(house3, 2);

        mapReduceDriver.addOutput(new Text(house1), new VectorWritable(cooccurrenceRow1));
        mapReduceDriver.addOutput(new Text(house2), new VectorWritable(cooccurrenceRow2));
        mapReduceDriver.addOutput(new Text(house3), new VectorWritable(cooccurrenceRow3));

        mapReduceDriver.runTest(false);

    }
}


text:
var DateRangePicker = require('./lib/components/DateRangePicker').default;
var DateRangePickerInput = require('./lib/components/DateRangePickerInput').default;
var DateRangePickerInputController = require('./lib/components/DateRangePickerInputController').default;
var SingleDatePicker = require('./lib/components/SingleDatePicker').default;
var SingleDatePickerInput = require('./lib/components/SingleDatePickerInput').default;
var DayPicker = require('./lib/components/DayPicker').default;
var DayPickerRangeController = require('./lib/components/DayPickerRangeController').default;
var CalendarMonthGrid = require('./lib/components/CalendarMonthGrid').default;
var CalendarMonth = require('./lib/components/CalendarMonth').default;
var CalendarDay = require('./lib/components/CalendarDay').default;

var DateRangePickerShape = require('./lib/shapes/DateRangePickerShape').default;
var SingleDatePickerShape = require('./lib/shapes/SingleDatePickerShape').default;

var isInclusivelyAfterDay = require('./lib/utils/isInclusivelyAfterDay').default;
var isInclusivelyBeforeDay = require('./lib/utils/isInclusivelyBeforeDay').default;
var isNextDay = require('./lib/utils/isNextDay').default;
var isSameDay = require('./lib/utils/isSameDay').default;

var toISODateString = require('./lib/utils/toISODateString').default;
var toLocalizedDateString = require('./lib/utils/toLocalizedDateString').default;
var toMomentObject = require('./lib/utils/toMomentObject').default;

module.exports = {
  DateRangePicker: DateRangePicker,
  SingleDatePicker: SingleDatePicker,

  DateRangePickerInputController: DateRangePickerInputController,
  DateRangePickerInput: DateRangePickerInput,
  SingleDatePickerInput: SingleDatePickerInput,
  DayPicker: DayPicker,
  DayPickerRangeController: DayPickerRangeController,
  CalendarMonthGrid: CalendarMonthGrid,
  CalendarMonth: CalendarMonth,
  CalendarDay: CalendarDay,

  DateRangePickerShape: DateRangePickerShape,
  SingleDatePickerShape: SingleDatePickerShape,

  isInclusivelyAfterDay: isInclusivelyAfterDay,
  isInclusivelyBeforeDay: isInclusivelyBeforeDay,
  isNextDay: isNextDay,
  isSameDay: isSameDay,

  toISODateString: toISODateString,
  toLocalizedDateString: toLocalizedDateString,
  toMomentObject: toMomentObject,
};


text:
$(function () {
    "use strict";

    settings.onSetBaseUrl(function (url) {
        var addTicketToHistory,
            removeTicketFromHistory;

        addTicketToHistory = function (ticket) {
            if ($('#recent_' + ticket.number).length > 0) {
                return;
            }
            $('#recent_table').append(
                '
'
                    + '#' + ticket.number + '	'
                    + '' + ticket.text + '	'
                    + '	'
                    + '	'
                    + '
'
            );

            favorites.each(function (ticket) {
                $('#recent_' + ticket.number + ' .favorite').removeClass('fa-star-o').addClass('fa-star');
            }, ticket.number);
            logging.each(function (ticket) {
                if (ticket.running) {
                    $('#recent_' + ticket.number + ' .log').removeClass('fa-play').addClass('fa-pause');
                }
            }, ticket.number);
        };
        removeTicketFromHistory = function (ticketNumber) {
            $('#recent_' + ticketNumber).remove();
        };

        ticketHistory.each(addTicketToHistory);
        ticketHistory.onAdded(addTicketToHistory);
        ticketHistory.onRemoved(removeTicketFromHistory);
    });

    favorites.onAdded(function (ticket) {
        $('#recent_' + ticket.number + ' .favorite').removeClass('fa-star-o').addClass('fa-star');
    });
    favorites.onRemoved(function (ticketNumber) {
        $('#recent_' + ticketNumber + ' .favorite').removeClass('fa-star').addClass('fa-star-o');
    });
    logging.onStarted(function (ticket) {
        $('#recent_' + ticket.number + ' .log').removeClass('fa-play').addClass('fa-pause');
    });
    logging.onResumed(function (ticket) {
        $('#recent_' + ticket.number + ' .log').removeClass('fa-play').addClass('fa-pause');
    });
    logging.onStopped(function (ticket) {
        $('#recent_' + ticket.number + ' .log').removeClass('fa-pause').addClass('fa-play');
    });
    logging.onRemoved(function (ticketNumber) {
        $('#recent_' + ticketNumber + ' .log').removeClass('fa-pause').addClass('fa-play');
    });
});


text:
<?php

/* SonataAdminBundle:CRUD:show_boolean.html.twig */
class __TwigTemplate_9ca7f8a05497f949941e19bd2ec3a9ebe4a6df85a5dbc02e3aa8d1f1da302c7a extends Twig_Template
{
    public function __construct(Twig_Environment $env)
    {
        parent::__construct($env);

        // line 12
        $this->parent = $this->loadTemplate("SonataAdminBundle:CRUD:base_show_field.html.twig", "SonataAdminBundle:CRUD:show_boolean.html.twig", 12);
        $this->blocks = array(
            'field' => array($this, 'block_field'),
        );
    }

    protected function doGetParent(array $context)
    {
        return "SonataAdminBundle:CRUD:base_show_field.html.twig";
    }

    protected function doDisplay(array $context, array $blocks = array())
    {
        $this->parent->display($context, array_merge($this->blocks, $blocks));
    }

    // line 14
    public function block_field($context, array $blocks = array())
    {
        // line 15
        ob_start();
        // line 16
        echo "    ";
        if ((isset($context["value"]) ? $context["value"] : $this->getContext($context, "value"))) {
            // line 17
            echo "        ";
            // line 18
            echo $this->env->getExtension('translator')->getTranslator()->trans("label_type_yes", array(), "SonataAdminBundle");
        } else {
            // line 20
            echo "        ";
            // line 21
            echo $this->env->getExtension('translator')->getTranslator()->trans("label_type_no", array(), "SonataAdminBundle");
        }
        echo trim(preg_replace('/>\s+</', '><', ob_get_clean()));
    }

    public function getTemplateName()
    {
        return "SonataAdminBundle:CRUD:show_boolean.html.twig";
    }

    public function isTraitable()
    {
        return false;
    }

    public function getDebugInfo()
    {
        return array (  43 => 21,  41 => 20,  38 => 18,  36 => 17,  33 => 16,  31 => 15,  28 => 14,  11 => 12,);
    }
}


text:
# Clevis/PushNotifications

A bundle to allow sending of push notifications to mobile devices.  Currently supports Android (C2DM, GCM), Blackberry and iOS devices.

## Installation

To use this bundle in your Nette project add the following to your `composer.json`:

```json
{
    "require": {
        "clevis/push-notifications": "~0.1-beta"
    }
}
```

and enable it in your config:

```yml
extensions:
	pushNotifications: Clevis\PushNotifications\DI\PushNotificationsExtension

pushNotifications:
    android:
        c2dm:
            username:
            password:
            source:
        gcm:
            apiKey:
    apple:
        sandbox: # boolean
        pem: # path to certificate
        passphrase:
```

NOTE: If you are using Windows, you may need to set the Android GCM `use_multi_curl` flag to false for GCM messages to be sent correctly.

## Usage

A little example of how to push your first message to an iOS device, we'll assume that you've set up the configuration correctly:

    use Clevis\PushNotifications\Message\iOSMessage;
    use Clevis\PushNotifications\Notifications;

    class Service
    {

	    /**
	     * @var Notifications
	     */
	    protected $sender;

        public function __construct(Notifications $sender)
        {
            $this->sender = $sender;
        }

        public function sendPushNotificationExample()
        {
            $message = new iOSMessage();
            $message->setMessage('Oh my! A push notification!');
            $message->setDeviceIdentifier('test012fasdf482asdfd63f6d7bc6d4293aedd5fb448fe505eb4asdfef8595a7');

            $this->sender->send($message);
        }
    }

The send method will detect the type of message so if you'll pass it an `AndroidMessage` it will automatically send it through the C2DM/GCM servers, and likewise for Mac and Blackberry.

## Android messages

Since both C2DM and GCM are still available, the `AndroidMessage` class has a small flag on it to toggle which service to send it to.  Use as follows:

```php
use Clevis\PushNotificationsBundle\Message\AndroidMessage;

$message = new AndroidMessage();
$message->setGCM(true);
```

to send as a GCM message rather than C2DM.

## iOS Feedback service

The Apple Push Notification service also exposes a Feedback service where you can get information about failed push notifications - see [here](https://developer.apple.com/library/ios/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/Chapters/CommunicatingWIthAPS.html#//apple_ref/doc/uid/TP40008194-CH101-SW3) for further details.

This service is available within the bundle.  The following code demonstrates how you can retrieve data from the service:

```php
$feedbackService = $container->get("rms_push_notifications.ios.feedback");
$uuids = $feedbackService->getDeviceUUIDs();
```

Here, `$uuids` contains an array of [Feedback](https://github.com/richsage/RMSPushNotificationsBundle/blob/master/Device/iOS/Feedback.php) objects, with timestamp, token length and the device UUID all populated.

Apple recommend you poll this service daily.


text:
<?php

namespace PayPal\Test\Api;

use PayPal\Api\CreditCard;

/**
 * Class CreditCard
 *
 * @package PayPal\Test\Api
 */
class CreditCardTest extends \PHPUnit_Framework_TestCase
{
    /**
     * Gets Json String of Object CreditCard
     *
     * @return string
     */
    public static function getJson()
    {
        return '{"id":"TestSample","number":"TestSample","type":"TestSample","expire_month":123,"expire_year":123,"cvv2":"TestSample","first_name":"TestSample","last_name":"TestSample","billing_address":' . AddressTest::getJson() . ',"external_customer_id":"TestSample","state":"TestSample","valid_until":"TestSample","links":' . LinksTest::getJson() . '}';
    }

    /**
     * Gets Object Instance with Json data filled in
     *
     * @return CreditCard
     */
    public static function getObject()
    {
        return new CreditCard(self::getJson());
    }

    /**
     * Tests for Serialization and Deserialization Issues
     *
     * @return CreditCard
     */
    public function testSerializationDeserialization()
    {
        $obj = new CreditCard(self::getJson());
        $this->assertNotNull($obj);
        $this->assertNotNull($obj->getId());
        $this->assertNotNull($obj->getNumber());
        $this->assertNotNull($obj->getType());
        $this->assertNotNull($obj->getExpireMonth());
        $this->assertNotNull($obj->getExpireYear());
        $this->assertNotNull($obj->getCvv2());
        $this->assertNotNull($obj->getFirstName());
        $this->assertNotNull($obj->getLastName());
        $this->assertNotNull($obj->getBillingAddress());
        $this->assertNotNull($obj->getExternalCustomerId());
        $this->assertNotNull($obj->getState());
        $this->assertNotNull($obj->getValidUntil());
        $this->assertNotNull($obj->getLinks());
        $this->assertEquals(self::getJson(), $obj->toJson());
        return $obj;
    }

    /**
     * @depends testSerializationDeserialization
     * @param CreditCard $obj
     */
    public function testGetters($obj)
    {
        $this->assertEquals($obj->getId(), "TestSample");
        $this->assertEquals($obj->getNumber(), "TestSample");
        $this->assertEquals($obj->getType(), "TestSample");
        $this->assertEquals($obj->getExpireMonth(), 123);
        $this->assertEquals($obj->getExpireYear(), 123);
        $this->assertEquals($obj->getCvv2(), "TestSample");
        $this->assertEquals($obj->getFirstName(), "TestSample");
        $this->assertEquals($obj->getLastName(), "TestSample");
        $this->assertEquals($obj->getBillingAddress(), AddressTest::getObject());
        $this->assertEquals($obj->getExternalCustomerId(), "TestSample");
        $this->assertEquals($obj->getState(), "TestSample");
        $this->assertEquals($obj->getValidUntil(), "TestSample");
        $this->assertEquals($obj->getLinks(), LinksTest::getObject());
    }

}


text:
<?php

defined('BASEPATH') OR exit('No direct script access allowed');

class Laminacao extends CI_Controller {

    function __construct() {
        parent::__construct();
        $this->load->model('Laminacao_m');
        empty($_SESSION) ? session_start() : '';
        login_necessario();
    }

    public function index() {
        $data['laminacao'] = $this->Laminacao_m->listar();
        $this->load->view('laminacao/lista', $data);
    }

    public function form() {
        $id = $this->uri->segment(3);

        if (empty($id)) {
            $data['acao'] = 'inserir';

            $this->load->view('laminacao/form', $data);
        } else {
            $laminacao = $this->Laminacao_m->listar($id);

            $data['laminacao'] = $laminacao[0];
            $data['acao'] = 'editar';
            $data['id'] = $id;

            $this->load->view('laminacao/form', $data);
        }
    }

    public function inserir() {
        $laminacao = new Laminacao_m();
        $laminacao->id = null;
        $laminacao->nome = $this->input->post('nome');
        $laminacao->descricao = $this->input->post('descricao');
        $laminacao->valor = $this->input->post('valor');

        $id = $this->Laminacao_m->inserir($laminacao);
        if (!empty($id)) {
            redirect(base_url('laminacao/?type=sucesso'), 'location');
        } else {
            redirect(base_url('laminacao/?type=erro'), 'location');
        }
    }

    public function editar() {
        $laminacao = new Laminacao_m();
        $laminacao->id = $this->input->post('id');
        ;
        $laminacao->nome = $this->input->post('nome');
        $laminacao->descricao = $this->input->post('descricao');
        $laminacao->valor = $this->input->post('valor');

        if ($this->Laminacao_m->editar($laminacao)) {
            redirect(base_url('laminacao/?type=sucesso'), 'location');
        } else {
            redirect(base_url('laminacao/?type=erro'), 'location');
        }
    }

    public function deletar() {
        $id = $this->uri->segment(3);

        if ($this->Laminacao_m->deletar($id)) {
            redirect(base_url('laminacao/?type=sucesso'), 'location');
        } else {
            redirect(base_url('laminacao/?type=erro'), 'location');
        }
    }

}


text:
var get = Ember.get, set = Ember.set;
var indexOf = Ember.EnumerableUtils.indexOf;

var Person, array, store;

var adapter = DS.Adapter.extend({
  deleteRecord: function(){
    return Ember.RSVP.Promise.resolve();
  }
});

module("unit/adapter_populated_record_array - DS.AdapterPopulatedRecordArray", {
  setup: function() {

    store = createStore({
      adapter: adapter
    });

    array = [{ id: '1', name: "Scumbag Dale" },
             { id: '2', name: "Scumbag Katz" },
             { id: '3', name: "Scumbag Bryn" }];

    Person = DS.Model.extend({
      name: DS.attr('string')
    });
  }
});

test("when a record is deleted in an adapter populated record array, it should be removed", function() {
  var recordArray = store.recordArrayManager
    .createAdapterPopulatedRecordArray(Person, null);

  Ember.run(function(){
    recordArray.load(array);
  });

  equal(recordArray.get('length'), 3, "expected recordArray to contain exactly 3 records");

  Ember.run(function(){
    recordArray.get('firstObject').destroyRecord();
  })

  equal(recordArray.get('length'), 2, "expected recordArray to contain exactly 2 records");
});


text:
package javax.validation;

/**
 * @version $Rev$ $Date$
 */
public interface ConstraintValidatorContext {
    void disableDefaultConstraintViolation();

    String getDefaultConstraintMessageTemplate();

    ConstraintViolationBuilder buildConstraintViolationWithTemplate(String messageTemplate);

    /** @since 1.1 */
    <T> T unwrap(Class<T> type);

    interface ConstraintViolationBuilder {
        NodeBuilderDefinedContext addNode(String name);

        ConstraintValidatorContext addConstraintViolation();

        // @since 1.1

        NodeBuilderCustomizableContext addPropertyNode(String name);
        LeafNodeBuilderCustomizableContext addBeanNode();
        NodeBuilderDefinedContext addParameterNode(int index);

        interface NodeBuilderDefinedContext {
            NodeBuilderCustomizableContext addNode(String name);

            ConstraintValidatorContext addConstraintViolation();

            // @since 1.1

            NodeBuilderCustomizableContext addPropertyNode(String name);
            LeafNodeBuilderCustomizableContext addBeanNode();
        }

        interface NodeBuilderCustomizableContext {

            NodeContextBuilder inIterable();

            NodeBuilderCustomizableContext addNode(String name);

            ConstraintValidatorContext addConstraintViolation();

            // @since 1.1

            NodeBuilderCustomizableContext addPropertyNode(String name);
            LeafNodeBuilderCustomizableContext addBeanNode();
        }

        interface NodeContextBuilder {

            NodeBuilderDefinedContext atKey(Object key);

            NodeBuilderDefinedContext atIndex(Integer index);

            NodeBuilderCustomizableContext addNode(String name);

            ConstraintValidatorContext addConstraintViolation();

            // @since 1.1

            NodeBuilderCustomizableContext addPropertyNode(String name);
            LeafNodeBuilderCustomizableContext addBeanNode();
        }

        /** @since 1.1 */
        interface LeafNodeBuilderDefinedContext {
            ConstraintValidatorContext addConstraintViolation();
        }

        /** @since 1.1 */
        interface LeafNodeBuilderCustomizableContext {
            LeafNodeContextBuilder inIterable();
            ConstraintValidatorContext addConstraintViolation();
        }

        /** @since 1.1 */
        interface LeafNodeContextBuilder {
            LeafNodeBuilderDefinedContext atKey(Object key);
            LeafNodeBuilderDefinedContext atIndex(Integer index);
            ConstraintValidatorContext addConstraintViolation();
        }
    }
}


text:
using UnityEngine;
using UnityEditor.Graphing;

namespace UnityEditor.ShaderGraph
{
    [FormerName("UnityEngine.MaterialGraph.ViewDirectionNode")]
    [Title("Input", "Geometry", "View Direction")]
    class ViewDirectionNode : GeometryNode, IMayRequireViewDirection
    {
        private const int kOutputSlotId = 0;
        public const string kOutputSlotName = "Out";

        public ViewDirectionNode()
        {
            name = "View Direction";
            UpdateNodeAfterDeserialization();
        }

        public sealed override void UpdateNodeAfterDeserialization()
        {
            AddSlot(new Vector3MaterialSlot(
                    kOutputSlotId,
                    kOutputSlotName,
                    kOutputSlotName,
                    SlotType.Output,
                    Vector4.zero));
            RemoveSlotsNameNotMatching(new[] { kOutputSlotId });
        }

        public override string GetVariableNameForSlot(int slotId)
        {
            return string.Format("IN.{0}", space.ToVariableName(InterpolatorType.ViewDirection));
        }

        public NeededCoordinateSpace RequiresViewDirection(ShaderStageCapability stageCapability)
        {
            return space.ToNeededCoordinateSpace();
        }
    }
}


text:
package org.codegist.crest.param.matrixes.crest;

import org.codegist.crest.annotate.*;
import org.codegist.crest.param.matrixes.common.IEncodingsTest;

import java.util.Collection;

/**
 * @author laurent.gilles@codegist.org
 */
public class EncodingsTest extends IEncodingsTest<EncodingsTest.Encodings> {

    public EncodingsTest(CRestHolder crest) {
        super(crest, Encodings.class);
    }

    @EndPoint("{crest.server.end-point}")
    @Path("params/matrix/encoding")
    @GET
    public static interface Encodings extends IEncodingsTest.IEncodings {

        @Path("default")
        String defaults(
                @MatrixParam("p1") String p1,
                @MatrixParam("p2") Collection<String> p2);

        @Path("encoded")
        String encoded(
                @Encoded @MatrixParam("p1") String p1,
                @Encoded @MatrixParam("p2") Collection<String> p2);

    }
}


text:
% Quelques petits problèmes sympas…
% ASCII
% 10 octobre 2013

# Une histoire
## Une histoire
### Le vizir et le calife

Il était une fois…

## Une histoire
### Remplissage du plateau

À partir de la première case :

__1__ grain de riz, __2__ grains de riz, __4__ grains de riz, __8__
grains de riz…

## Une histoire
### Remplissage du plateau

À partir de la dixième case :

__512__ grains de riz, __1024__ grains de riz, __4096__ grains de riz,
__8192__ grains de riz…

## Une histoire
### Remplissage du plateau

La dernière case :

__9 223 372 036 854 775 808__ grains de riz

## Une histoire
### Remplissage du plateau

Pour un total de :

__18 446 744 073 709 551 615__ grains de riz

## Une histoire
### Remplissage du plateau

La quantité de riz __q(n)__ présente sur la case __n__ est __2n - 1__.

On dit que la fonction __q__ est __exponentielle__.

# Complexité
## Complexité
### Dire bonjour à des gens

Pour saluer une classe, un prof pourrait :

- saluer tout le monde d'un geste de la main
- saluer chaque élève individuellement
- ordonner les élèves par leur moyenne et les saluer un par un
- …

## Complexité
### Faire des choses sur un ordi

En fonction de comment on s'y prend, ça peut vite dégénérer.


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using Aspose.Imaging.Live.Demos.UI.Config;

namespace Aspose.Imaging.Live.Demos.UI.Models
{
	public class AnotherApp
	{
		public string ImageSource { get; set; }
		public string ImageAlt { get; set; }
		public string AppName { get; set; }
		public string Href { get; set; }

		public AnotherApp()
		{
			// Empty for inheritance
		}

		public AnotherApp(string product, string appName)
		{
			AppName = appName;
			Href = $"/{product}/{appName.ToLower()}";

			switch (product)
			{
				case "words":
				{
					ImageSource = $"/img/apps/aspose_{appName.ToLower()}-app.png";
					ImageAlt = $"Aspose.Words {AppName}";
					break;
				}
				case "pdf":
				{
					ImageSource = $"/img/apps/aspose_{appName.ToLower()}-app.png";
					ImageAlt = $"Aspose.PDF {AppName}";
					break;
				}
				default:
				{
					if (AppName == "OCR" && (product == "ocr"))
						ImageSource = @"../../img/ocr/ocr-recognize-48.png";
					else
						ImageSource =
							$"https://www.aspose.cloud/templates/asposeapp/images/products/logo/aspose_{appName.ToLower()}-app.png";
					ImageAlt = $"{AppName}";
					break;
				}
			}
		}
	}
}


text: export { default } from 'maverick-cli/components/mav-nav-horizontal';


text:
package org.apache.jackrabbit.vault.fs.config;

import java.io.ByteArrayOutputStream;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import javax.jcr.Credentials;
import javax.jcr.SimpleCredentials;
import javax.xml.stream.XMLStreamException;
import javax.xml.stream.XMLStreamWriter;

import org.apache.jackrabbit.vault.util.Text;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.ContentHandler;
import org.xml.sax.SAXException;

/**
 * {@code SimpleCredentialsConfig}...
*
*/
public class SimpleCredentialsConfig extends CredentialsConfig {

    /**
     * key length
     */
    private final static int KEY_LENGTH = 8;

    /**
     * encryption prefix
     */
    private final static String PREFIX = "{DES}";

    /**
     * default logger
     */
    private static final Logger log = LoggerFactory.getLogger(SimpleCredentialsConfig.class);

    private final SimpleCredentials creds;
    public static final String ELEM_USER = "user";
    public static final String ATTR_NAME = "name";
    public static final String ATTR_PASSWORD = "password";

    public SimpleCredentialsConfig(SimpleCredentials creds) {
        super("simple");
        this.creds = creds;
    }

    public Credentials getCredentials() {
        return creds;
    }

    public static SimpleCredentialsConfig load(Element elem) throws ConfigurationException {
        assert elem.getNodeName().equals(ELEM_CREDETIALS);

        NodeList nl = elem.getChildNodes();
        for (int i=0; i<nl.getLength(); i++) {
            Node child = nl.item(i);
            if (child.getNodeType() == Node.ELEMENT_NODE) {
                if (child.getNodeName().equals(ELEM_USER)) {
                    Element e = (Element) child;
                    String name = e.getAttribute(ATTR_NAME);
                    String pass = decrypt(e.getAttribute(ATTR_PASSWORD));
                    return new SimpleCredentialsConfig(
                            new SimpleCredentials(
                                    name,
                                    pass == null ? new char[0] : pass.toCharArray()));
                }
            }
        }
        throw new ConfigurationException("mandatory element <user> missing.");
    }

    @Deprecated
    public void writeInner(ContentHandler handler) throws SAXException {
        throw new UnsupportedOperationException("No longer supports write with a SAX contentHandler, user write with XMLStreamWriter instead!");
    }

    @Override
    protected void writeInner(XMLStreamWriter writer) throws XMLStreamException {
        if (creds != null) {
            writer.writeStartElement(ELEM_USER);
            writer.writeAttribute(ATTR_NAME, creds.getUserID());
            writer.writeAttribute(ATTR_PASSWORD, encrypt(new String(creds.getPassword())));
            writer.writeEndElement();
        }
    }

    /**
     * Encrypts the given string in a fairly secure way so that it can be
     * {@link #decrypt(String) decrypted} again.
     *
     * @param s string to encrypt
     * @return the encrypted string with a "{AES}" prefix.
     */
    private static String encrypt(String s) {
        try {
            SecretKey key = KeyGenerator.getInstance("DES").generateKey();
            Cipher cipher = Cipher.getInstance("DES");
            byte[] keyBytes = key.getEncoded();
            byte[] data = s.getBytes("utf-8");
            ByteArrayOutputStream out = new ByteArrayOutputStream(keyBytes.length + data.length);
            out.write(keyBytes);
            cipher.init(Cipher.ENCRYPT_MODE, key);
            out.write(cipher.update(data));
            out.write(cipher.doFinal());
            StringBuilder ret = new StringBuilder(PREFIX);
            for (byte b: out.toByteArray()) {
                ret.append(Text.hexTable[b>>4 & 0x0f]).append(Text.hexTable[b&0x0f]);
            }
            return ret.toString();
        } catch (Exception e) {
            log.warn("Unable to encrypt string: " + e);
            return null;
        }
    }

    /**
     * Decrypts a string that was previously {@link #encrypt(String)} encrypted}.
     *
     * @param s the data to decrypt
     * @return the string or {@code null} if an internal error occurred
     */
    private static String decrypt(String s) {
        if (s == null || !s.startsWith(PREFIX)) {
            return s;
        }
        try {
            byte[] data = new byte[(s.length() - PREFIX.length())/2];
            for (int i=PREFIX.length(),b=0; i<s.length(); i+=2, b++) {
                data[b] = (byte) (Integer.parseInt(s.substring(i, i+2), 16) &0xff);
            }
            SecretKeySpec key = new SecretKeySpec(data, 0, KEY_LENGTH, "DES");
            Cipher cipher = Cipher.getInstance("DES");
            try (ByteArrayOutputStream out = new ByteArrayOutputStream(data.length)) {
                cipher.init(Cipher.DECRYPT_MODE, key);
                out.write(cipher.update(data, KEY_LENGTH, data.length - KEY_LENGTH));
                out.write(cipher.doFinal());
                return out.toString("utf-8");
            }
        } catch (Exception e) {
            log.warn("Unable to decrypt data: " + e);
            return null;
        }
    }

}


text:
@extends('layout')

@section('title', "Search for $term -")

@section('content')
    @forelse ($results as $agenda_item)
        @include('agendaItemPartial', [ 'agenda_item' => $agenda_item, 'show_meeting' => true ])
    @empty
        No results found for {{ $term }}
    @endforelse

@stop


text:
export { default as createService } from './create-service';
export { default as deleteService } from './delete-service';

// Tag mutations
export { default as createTag } from './create-tag';
export { default as deleteTag } from './delete-tag';


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
in Cohn, Krypt. -Fl. Schlesien (Breslau) 3. 1(17–24): 352 (1887)

#### Original name
Phragmidium sanguisorbae var. sanguisorbae

### Remarks
null


text:
package honeycomb

import (
	"net/url"
	"sync"

	honeycomb_common "github.com/Stackdriver/heapster/common/honeycomb"
	"github.com/Stackdriver/heapster/metrics/core"
	"k8s.io/klog"
)

// These metrics report cumulative values over the lifetime of the process.
// Heapster also reports gauges (e.g., "cpu/usage_rate"). Cumulative metrics
// are more confusing than helpful, so let's not send them in the first place.
var denylist = map[string]struct{}{
	"cpu/usage":                {},
	"memory/major_page_faults": {},
	"memory/page_faults":       {},
	"network/rx_errors":        {},
	"network/rx":               {},
	"network/tx_errors":        {},
	"network/tx":               {},
}

type honeycombSink struct {
	client honeycomb_common.Client
	sync.Mutex
}

type Point struct {
	MetricsName string
	MetricsTags string
}

func (sink *honeycombSink) ExportData(dataBatch *core.DataBatch) {

	sink.Lock()
	defer sink.Unlock()

	batch := make(honeycomb_common.Batch, len(dataBatch.MetricSets))

	i := 0
	for _, metricSet := range dataBatch.MetricSets {
		data := make(map[string]interface{})
		for metricName, metricValue := range metricSet.MetricValues {
			if _, ok := denylist[metricName]; ok {
				continue
			}
			data[metricName] = metricValue.GetValue()
		}
		for k, v := range metricSet.Labels {
			data[k] = v
		}
		batch[i] = &honeycomb_common.BatchPoint{
			Data:      data,
			Timestamp: dataBatch.Timestamp,
		}
		i++
	}
	err := sink.client.SendBatch(batch)
	if err != nil {
		klog.Warningf("Failed to send metrics batch: %v", err)
	}
}

func (sink *honeycombSink) Stop() {}
func (sink *honeycombSink) Name() string {
	return "Honeycomb Sink"
}

func NewHoneycombSink(uri *url.URL) (core.DataSink, error) {
	client, err := honeycomb_common.NewClient(uri)
	if err != nil {
		return nil, err
	}
	sink := &honeycombSink{
		client: client,
	}

	return sink, nil
}


text:
'use strict';

const ReduktPlugin = require('./ReduktPlugin');
const Env = require('../builder/Env');
const webpack = require('webpack');

/**
 * @class
 */
class Hmr extends ReduktPlugin {
	/**
	 * Adds the HMR client script to each entry point.
	 *
	 * @public
	 * @param {{}} entry
	 * @return {{}}
	 */
	static addClient(entry) {
		const results = {};

		Object.keys(entry).forEach((name) => {
			results[name] = Array.isArray(entry[name]) ? entry[name].slice(0) : [entry[name]];
			results[name].unshift(`${__dirname}/../plugins/HmrClient.js`);
		});

		return results;
	}

	/**
	 * @inheritDoc
	 */
	isEnabled() {
		return Env.isWatching();
	}

	/**
	 * @inheritDoc
	 */
	plugin() {
		return new webpack.HotModuleReplacementPlugin();
	}
}

module.exports = Hmr;


text:
<?php

use yii\apidocchm\helpers\ApiMarkdown;
use yii\apidocchm\models\ClassDoc;
use yii\helpers\ArrayHelper;

/* @var $type ClassDoc */
/* @var $this yii\web\View */
/* @var $renderer \yii\apidocchm\templates\html\ApiRenderer */

$renderer = $this->context;

$events = $type->getNativeEvents();
if (empty($events)) {
    return;
}
ArrayHelper::multisort($events, 'name');
?>

Event Details

<?php foreach ($events as $event): ?>
    <div class="detail-header h3" id="<?= $event->name.'-detail' ?>">

        <?= $renderer->createSubjectLink($event, '', [
            'title' => 'direct link to this method',
            'class' => 'tool-link hash',
        ]) ?>

        <?php if (($sourceUrl = $renderer->getSourceUrl($event->definedBy, $event->startLine)) !== null): ?>
            <a href="<?= str_replace('/blob/', '/edit/', $sourceUrl) ?>" class="tool-link" title="edit on github">
            <a href="<?= $sourceUrl ?>" class="tool-link" title="view source on github">
        <?php endif; ?>

        <?= $event->name ?>

        event
        of type <?= $renderer->createTypeLink($event->types) ?>
        <?php if (!empty($event->since)): ?>
            (available since version <?= $event->since ?>)
        <?php endif; ?>

        <?= ApiMarkdown::process($event->description, $type) ?>

        <?= $this->render('seeAlso', ['object' => $event]) ?>

<?php endforeach; ?>


text:
<meta http-equiv="Content-Type" content="text/html; charset=US-ASCII">
<title>Macro BOOST_LOG_COMBINE_REQUIREMENTS_LIMIT</title>
<link rel="stylesheet" href="../../../../doc/src/boostbook.css" type="text/css">
<meta name="generator" content="DocBook XSL Stylesheets V1.78.1">
<link rel="home" href="index.html" title="Chapter 1. Boost.Log v2">
<link rel="up" href="sinks.html#header.boost.log.sinks.frontend_requirements_hpp" title="Header <boost/log/sinks/frontend_requirements.hpp>">
<link rel="prev" href="boost/log/sinks/has_requirement.html" title="Struct template has_requirement">
<link rel="next" href="boost/log/sinks/sink.html" title="Class sink">

Macro BOOST_LOG_COMBINE_REQUIREMENTS_LIMIT

BOOST_LOG_COMBINE_REQUIREMENTS_LIMIT — The macro specifies the maximum number of requirements that can be combined with the combine_requirements metafunction.

Synopsis

// In header: <boost/log/sinks/frontend_requirements.hpp>

BOOST_LOG_COMBINE_REQUIREMENTS_LIMIT

Copyright © 2007-2014 Andrey Semashev

        Distributed under the Boost Software License, Version 1.0. (See accompanying
        file LICENSE_1_0.txt or copy at http://www.boost.org/LICENSE_1_0.txt).


text:
#import "../AmazonServiceRequest.h"

#import "AutoScalingRequest.h"
#import "AutoScalingDescribePoliciesRequest.h"

/**
 * Describe Policies Request Marshaller
 */
@interface AutoScalingDescribePoliciesRequestMarshaller:NSObject {
}

+(AmazonServiceRequest *)createRequest:(AutoScalingDescribePoliciesRequest *)describePoliciesRequest;

@end


text:
// Copyright 2013 The Chromium Authors
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package org.chromium.android_webview.test.util;

import android.support.test.InstrumentationRegistry;

import org.chromium.android_webview.AwQuotaManagerBridge;
import org.chromium.base.test.util.CallbackHelper;

/**
 * This class provides common methods for AwQuotaManagerBridge related tests
 */
public class AwQuotaManagerBridgeTestUtil {
    private static class GetOriginsCallbackHelper extends CallbackHelper {
        private AwQuotaManagerBridge.Origins mOrigins;

        public void notifyCalled(AwQuotaManagerBridge.Origins origins) {
            mOrigins = origins;
            notifyCalled();
        }

        public AwQuotaManagerBridge.Origins getOrigins() {
            assert getCallCount() > 0;
            return mOrigins;
        }
    }

    public static AwQuotaManagerBridge.Origins getOrigins(AwQuotaManagerBridge bridge)
            throws Exception {
        final GetOriginsCallbackHelper callbackHelper = new GetOriginsCallbackHelper();

        int callCount = callbackHelper.getCallCount();
        InstrumentationRegistry.getInstrumentation().runOnMainSync(
                () -> bridge.getOrigins(origins -> callbackHelper.notifyCalled(origins)));
        callbackHelper.waitForCallback(callCount);

        return callbackHelper.getOrigins();
    }
}


text:
<% var togglerId = _.uniqueId('dropdown-') %>

    <a href="#" role="button" class="dropdown-toggle dropdown-toggle--no-caret" id="<%- togglerId %>" data-toggle="dropdown"
            data-modifiers="<%- JSON.stringify({preventOverflow: {enabled: false}, hide: {enabled: false}}) %>"
            aria-haspopup="true" aria-expanded="false"
            aria-label="<%- _.__('oro.datagrid.headerCell.selectAll.label') %>"><input type="checkbox" data-select/>

    <ul class="dropdown-menu dropdown-menu__select-all-header-cell" aria-labelledby="<%- togglerId %>">

<%- _.__('oro.datagrid.headerCell.selectAll.all') %>

<%- _.__('oro.datagrid.headerCell.selectAll.allVisible') %>

<%- _.__('oro.datagrid.headerCell.selectAll.none') %>


text:
from __future__ import print_function

import collections
import os
import sys
import textwrap

import yaml
import docker

_dockerclient = None

def get_client_api():
    return get_client().api

def get_client():
    global _dockerclient

    if _dockerclient is None:
        _dockerclient = docker.from_env(version='auto')

    return _dockerclient

def list_image_defs(args, defs):
    from . import imagedefs

    print('TARGETS in `%s`' % args.makefile)
    for item in sorted(defs.ymldefs.keys()):
        if item in imagedefs.SPECIAL_FIELDS:
            continue
        print(' *', item)
    return

def generate_name(image, args):
    repo_base = args.repository

    if repo_base is not None:
        if repo_base[-1] not in ':/':
            repo_base += '/'
        repo_name = repo_base + image
    else:
        repo_name = image

    if args.tag:
        if ':' in repo_name:
            repo_name += '-'+args.tag
        else:
            repo_name += ':'+args.tag

    return repo_name

def get_build_targets(args, defs):
    if args.requires or args.name:
        # Assemble a custom target from requirements
        assert args.requires and args.name
        assert args.name not in defs.ymldefs
        defs.ymldefs[args.name] = {'requires': args.requires,
                                   '_sourcefile': "command line arguments"}
        targets = [args.name]

    elif args.all:
        # build all targets in the file
        assert len(args.TARGETS) == 0, "Pass either a list of targets or `--all`, not both"
        if defs.all_targets is not None:
            targets = defs.all_targets
        else:
            targets = list(defs.ymldefs.keys())
    else:
        # build the user-specified targets
        targets = args.TARGETS

    return targets

def build_targets(args, defs, targets):
    if args.no_build:
        client = None
    else:
        client = get_client_api()

    if args.push_to_registry and args.registry_user:
        if not args.repository:
            raise ValueError('No registry specified to push images to.')
        registry = args.repository.split('/')[0]
        client.login(args.registry_user,
                     password=args.registry_token,
                     registry=registry,
                     reauth=True)
        print("\nREGISTRY LOGIN SUCCESS:",registry)

    built, warnings = [], []
    builders = [defs.generate_build(t, generate_name(t, args), rebuilds=args.bust_cache)
                for t in targets]
    for b in builders:
        b.build(client,
                nobuild=args.no_build,
                usecache=not args.no_cache,
                pull=args.pull)
        if not args.no_build:
            print('  docker-make built:', b.targetname)

        if args.print_dockerfiles or args.no_build:
            b.write_dockerfile(args.dockerfile_dir)

        built.append(b.targetname)
        if args.push_to_registry and not args.no_build:
            success, w = push(client, b.targetname)
            warnings.extend(w)
            if not success:
                built[-1] += ' -- PUSH FAILED'
            else:
                built[-1] += ' -- pushed to %s' % b.targetname.split('/')[0]

    return built, warnings

def push(client, name):
    success = False
    warnings = []
    if '/' not in name or name.split('/')[0].find('.') < 0:
        warn = 'WARNING: could not push %s - ' \
               'repository name does not contain a registry URL' % name
        warnings.append(warn)
        print(warn)
    else:
        print('  Pushing %s to %s:' % (name, name.split('/')[0]))
        stream = _linestream(client.push(name, stream=True))
        line = stream_docker_logs(stream, 'PUSH %s' % name)

        if 'error' in line:
            warnings.append('WARNING: push failed for %s. Message: %s' % (name, line['error']))
        else:
            success = True
    return success, warnings

def _linestream(textstream):
    for item in textstream:
        for line in item.splitlines():
            yield yaml.load(line)

def human_readable_size(num, suffix='B'):
    """ FROM http://stackoverflow.com/a/1094933/1958900
    """
    for unit in ['','Ki','Mi','Gi','Ti','Pi','Ei','Zi']:
        if abs(num) < 1024.0:
            return "%3.1f%s%s" % (num, unit, suffix)
        num /= 1024.0
    return "%.1f%s%s" % (num, 'Yi', suffix)

def stream_docker_logs(stream, name):
    textwidth = get_console_width() - 5
    if textwidth <= 2:
        textwidth = 100
    wrapper = textwrap.TextWrapper(initial_indent='  ',
                                   subsequent_indent='  ',
                                   break_on_hyphens=False,
                                   width=textwidth)

    logtitle = '%s: BUILD LOG' % name
    numdash = (textwidth - len(logtitle) - 7) // 2
    header = ''.join(['  ','-'*numdash, "   %s   " % logtitle, '-'*numdash])
    print(header)

    pullstats = collections.OrderedDict()
    for item in stream:
        if list(item.keys()) == ['stream']:
            line = item['stream'].strip()
        elif 'errorDetail' in item or 'error' in item:
            raise ValueError(item)
        elif 'status' in item and 'id' in item:  # for pulling images
            line = _show_xfer_state(pullstats, item)
            if line is None: continue
        else:
            line = str(item)

        for s in wrapper.wrap(line):
            print(s)

    print(' ', '-'*len(header))
    return line

def get_console_width():
    try:
        _, consolewidth = map(int, os.popen('stty size 2> /dev/null', 'r').read().split())
    except:
        consolewidth = 80
    return consolewidth

SHOWSIZE = set(('Pushing', 'Pulling', 'Pulled', 'Downloaded', 'Downloading'))

def _show_xfer_state(pullstats, item):
    imgid = item['id']
    stat = item['status']
    if stat != pullstats.get(imgid, None):
        pullstats[imgid] = stat

        if stat in SHOWSIZE and item.get('progressDetail', {}).get('total', None):
            toprint = '%s: %s (%s)' % (imgid, stat,
                                       human_readable_size(item['progressDetail']['total']))
        else:
            toprint = '%s: %s' % (imgid, stat)

        return toprint
    else:
        return None


text:
layout: default
title: CAS - Long Term Authentication
---

# Long Term Authentication
This feature, also known as *Remember Me*, extends the length of the SSO session beyond the typical period of hours
such that users can go days or weeks without having to log in to CAS. See the
[security guide](../planning/Security-Guide.html)
for discussion of security concerns related to long term authentication.

### Policy and Deployment Considerations
While users can elect to establish a long term authentication session, the duration is established through
configuration as a matter of security policy. Deployers must determine the length of long term authentication sessions
by weighing convenience against security risks. The length of the long term authentication session is configured
(somewhat unhelpfully) in seconds, but the Google calculator provides a convenient converter:

[2 weeks in seconds](https://www.google.com/search?q=2+weeks+in+seconds&oq=2+weeks+in+seconds)

The use of long term authentication sessions dramatically increases the length of time ticket-granting tickets are
stored in the ticket registry. Loss of a ticket-granting ticket corresponding to a long-term SSO session would require
the user to re-authenticate to CAS. A security policy that requires that long term authentication sessions MUST NOT
be terminated prior to their natural expiration would mandate a ticket registry component that provides for durable storage, such as the `JpaTicketRegistry`.

### Component Configuration
Long term authentication requires configuring CAS components in Spring configuration, modification of the CAS login
webflow, and UI customization of the login form. The length of the long term authentication session is represented
in following sections by the following property:

    # Long term authentication session length in seconds
    rememberMeDuration=1209600

The duration of the long term authentication session is configured in two different places:
1. `ticketExpirationPolicies.xml`
2. `ticketGrantingTicketCookieGenerator.xml`

Update the ticket-granting ticket expiration policy in `ticketExpirationPolicies.xml` to accommodate both long term
and stardard sessions.
{% highlight xml %}
<!--
   | The following policy applies to standard CAS SSO sessions.
   | Default 2h (7200s) sliding expiration with default 8h (28800s) maximum lifetime.
   -->
<bean id="standardSessionTGTExpirationPolicy"
      class="org.jasig.cas.ticket.support.TicketGrantingTicketExpirationPolicy"
      p:maxTimeToLiveInSeconds="${tgt.maxTimeToLiveInSeconds:28800}"
      p:timeToKillInSeconds="${tgt.timeToKillInSeconds:7200}"/>

<!--
   | The following policy applies to long term CAS SSO sessions.
   | Default duration is two weeks (1209600s).
   -->
<bean id="longTermSessionTGTExpirationPolicy"
      class="org.jasig.cas.ticket.support.TimeoutExpirationPolicy"
      c:timeToKillInMilliSeconds="#{ ${rememberMeDuration:1209600} * 1000 }" />

<bean id="grantingTicketExpirationPolicy"
      class="org.jasig.cas.ticket.support.RememberMeDelegatingExpirationPolicy"
      p:sessionExpirationPolicy-ref="standardSessionTGTExpirationPolicy"
      p:rememberMeExpirationPolicy-ref="longTermSessionTGTExpirationPolicy" />
{% endhighlight %}

Update the CASTGC cookie expiration in `ticketGrantingTicketCookieGenerator.xml` to match the long term authentication
duration:
{% highlight xml %}
<bean id="ticketGrantingTicketCookieGenerator" class="org.jasig.cas.web.support.CookieRetrievingCookieGenerator"
      p:cookieSecure="true"
      p:cookieMaxAge="-1"
      p:rememberMeMaxAge="${rememberMeDuration:1209600}"
      p:cookieName="CASTGC"
      p:cookiePath="/cas" />
{% endhighlight %}

Modify the `PolicyBasedAuthenticationManager` bean in `deployerConfigContext.xml` to include the
`RememberMeAuthenticationMetaDataPopulator` component that flags long-term SSO sessions:
{% highlight xml %}
<bean id="authenticationManager"
      class="org.jasig.cas.authentication.PolicyBasedAuthenticationManager">
  <constructor-arg>
    <map>
      <entry key-ref="passwordHandler" value-ref="ldapPrincipalResolver"/>
    </map>
  </constructor-arg>
  <property name="authenticationMetaDataPopulators">
    <list>
      <bean class="org.jasig.cas.authentication.SuccessfulHandlerMetaDataPopulator" />
      <bean class="org.jasig.cas.authentication.principal.RememberMeAuthenticationMetaDataPopulator" />
    </list>
  </property>
</bean>
{% endhighlight %}

### Webflow Configuration
Two sections of `login-webflow.xml` require changes:
1. `credential` variable declaration
2. `viewLoginForm` action state

Change the `credential` variable declaration as follows:
{% highlight xml %}
<var name="credential" class="org.jasig.cas.authentication.RememberMeUsernamePasswordCredential" />
{% endhighlight %}

Change the `viewLoginForm` action state as follows:
{% highlight xml %}
<view-state id="viewLoginForm" view="casLoginView" model="credential">
  <binder>
    <binding property="username" />
    <binding property="password" />
    <binding property="rememberMe" />
  </binder>
  <on-entry>
    <set name="viewScope.commandName" value="'credential'" />
  </on-entry>
  <transition on="submit" bind="true" validate="true" to="realSubmit"/>
</view-state>
{% endhighlight %}

### User Interface Customization
A checkbox or other suitable control must be added to the CAS login form to allow user selection of long term
authentication. We recommend adding a checkbox control to `casLoginView.jsp` as in the following code snippet.
The only functional consideration is that the name of the form element is _rememberMe_.
{% highlight xml %}
<input type="checkbox" name="rememberMe" id="rememberMe" value="true" />
<label for="rememberMe">Remember Me</label>
{% endhighlight %}


text:
package mezz.jei.common.util;

import net.minecraft.world.item.ItemStack;

public enum GiveAmount {
	ONE, MAX;

	public int getAmountForStack(ItemStack itemStack) {
		return switch (this) {
			case MAX -> itemStack.getMaxStackSize();
			case ONE -> 1;
		};
	}
}


text:
@interface XDKSaveTool : NSObject
+ (id)objectForKey:(NSString *)defaultName;

+ (void)setObject:(id)value forKey:(NSString *)defaultName;
@end


text:
require 'spec_helper'

describe "Client" do

  subject { page }
  before do
      sign_in_as_a_valid_user
  end

  describe "create new page" do
    before { visit new_client_path }
    it { should have_content('Crear Cliente Nuevo') }
    it { should have_title(full_title('Crear Cliente')) }
  end

  describe "register client" do
    before { visit new_client_path }
    let(:submit) { "Create Client" }

    describe "with invalid information" do
      it "should not create a client" do
        expect { click_button submit }.to_not change(Client, :count)
      end
    end

    describe "with valid information" do
      before do
        fill_in "client_name", with: "Example Name"
        fill_in "client_fullname", with: "Example Fullname"
        fill_in "client_ruc", with: "J1234567891112"
        fill_in "client_legalrepresentative", with: "John Example"
        fill_in "client_address", with: "Example Address"
        fill_in "client_web", with: "www.example.com"
      end

      it "should create a new client" do
        expect { click_button submit }.to change(Client, :count).by(1)
      end
    end
  end

end


text:
describe Fastlane::Actions::AutomatedTestEmulatorRunAction do
  describe '#run' do
    it 'prints a message' do
      expect(Fastlane::UI).to receive(:message).with("The automated_test_emulator_run plugin is working!")

      Fastlane::Actions::AutomatedTestEmulatorRunAction.run(nil)
    end
  end
end


text:
#include "tensorflow_federated/cc/core/impl/executors/session_provider.h"

#include <utility>

#include "googlemock/include/gmock/gmock.h"
#include "googletest/include/gtest/gtest.h"
#include "tensorflow_federated/cc/core/impl/executors/status_matchers.h"

namespace tensorflow_federated {

namespace {

TEST(SessionProviderTest, TestStandaloneTakeSession) {
  tensorflow::GraphDef graphdef_pb;
  SessionProvider session_provider(std::move(graphdef_pb), 1);
  TFF_ASSERT_OK(session_provider.TakeSession());
}

TEST(SessionProviderTest, TestSessionNotAvailableConcurrencyLimited) {
  tensorflow::GraphDef graphdef_pb;
  SessionProvider session_provider(std::move(graphdef_pb),
                                   /*max_active_sessions=*/1);
  TFF_ASSERT_OK(session_provider.TakeSession());
  EXPECT_EQ(session_provider.SessionOrCpuAvailable(), false);
}

TEST(SessionProviderTest, TestSessionAvailableConcurrencyUnlimited) {
  tensorflow::GraphDef graphdef_pb;
  SessionProvider session_provider(std::move(graphdef_pb), -1);
  TFF_ASSERT_OK(session_provider.TakeSession());
  EXPECT_EQ(session_provider.SessionOrCpuAvailable(), true);
}

TEST(SessionProviderTest, TestReturningSessionFreesUpAvailability) {
  tensorflow::GraphDef graphdef_pb;
  SessionProvider session_provider(std::move(graphdef_pb), 1);
  absl::StatusOr<SessionProvider::SessionWithResourceContainer> taken_session =
      session_provider.TakeSession();
  TFF_ASSERT_OK(taken_session.status());
  EXPECT_EQ(session_provider.SessionOrCpuAvailable(), false);
  session_provider.ReturnSession(std::move(taken_session.value()));
  EXPECT_EQ(session_provider.SessionOrCpuAvailable(), true);
}

}  // namespace
}  // namespace tensorflow_federated


text:
module ThreeScaleToolbox
  module Commands
    module BackendCommand
      module CopyCommand
        class CopyMetricsTask
          include Task

          # entrypoint
          def run
            missing_metrics.each(&method(:create_metric))
            logger.info "created #{missing_metrics.size} missing metrics"
            report['missing_metrics_created'] = missing_metrics.size
          end

          private

          def create_metric(metric)
            Entities::BackendMetric.create(backend: target_backend, attrs: metric.attrs)
          end

          def missing_metrics
            @missing_metrics ||= ThreeScaleToolbox::Helper.array_difference(source_backend.metrics, target_backend.metrics) do |s_m, t_m|
              s_m.system_name == t_m.system_name
            end
          end
        end
      end
    end
  end
end


text:
package com.softwaremill.common.cdi.conf;

import com.softwaremill.common.conf.Configuration;

import javax.enterprise.inject.Produces;
import javax.enterprise.inject.spi.InjectionPoint;
import java.util.Map;

public class ConfValueProducer {
    @Produces
    @ConfValue(confName = "", confKey = "")
    public String getConfigurationValue(InjectionPoint ip) {
        ConfValue confValue = ip.getAnnotated().getAnnotation(ConfValue.class);
        return Configuration.get(confValue.confName()).get(confValue.confKey());
    }

    public static String from(InjectionPoint ip, Map<String, String> configuration) {
        ConfValue confValue = ip.getAnnotated().getAnnotation(ConfValue.class);
        return configuration.get(confValue.confKey());
    }
}


text:
var gith = require('gith').create( 9002 );
// Import execFile, to run our bash script
var execFile = require('child_process').execFile;

// Auto deploy the server
gith({
    repo: 'thebillkidy/Feedient-Server',
    branch: 'production'
}).on( 'all', function( payload ) {
    // Exec a shell script
    execFile('/opt/git_hooks/deploy_server.sh', function(error, stdout, stderr) {
        // Log success in some manner
        console.log('deployed server');
    });
});


text: Just a simple Loopback LDAP connector


text:
@implementation ZFDeleteMessage

#if FL_MRC
- (void) dealloc {
    [_mailboxId release];
    [super dealloc];
}
#endif
+ (ZFDeleteMessage*) deleteMessage {
    return FLAutorelease([[[self class] alloc] init]);
}
@synthesize mailboxId = _mailboxId;
@synthesize messageIndex = _messageIndex;

@end


text:
/*
 * This file is part of the RMTopBarController project.
 *
 * (c) Robert Mogos
 *
 * This source file is subject to the MIT license that is bundled
 * with this source code in the file LICENSE.
 */

#import "RMTopBarController.h"

@interface RMTopBarController (PrivateMethods)
- (void)setupTopBar;
- (void)setupContainerView;
- (void)positionTopBar;

@end

@interface UIViewController (RMTopBarControllerItemPrivate)
- (RMTopBarController *) topBarControllerWithPostion:(RMTopBarPosition)postion;
@end

@implementation UIViewController (RMTopBarControllerItem)

- (RMTopBarController *) topBarController{
  return [self topBarControllerWithPostion:RMTopBarPositionTop];
}

- (RMTopBarController *) bottomBarController{
  return [self topBarControllerWithPostion:RMTopBarPositionBottom];
}

- (RMTopBarController *) topBarControllerWithPostion:(RMTopBarPosition)postion{

  UIViewController * ancestor = self.parentViewController;
  while (ancestor) {
    if ([ancestor isKindOfClass:[RMTopBarController class]] &&
        postion == [(RMTopBarController *)ancestor topBarPosition])

      return (RMTopBarController *)ancestor;

    ancestor = ancestor.parentViewController;
  }

  return nil;
}

@end

@implementation RMTopBarController
@synthesize selectedIndex = selectedIndex_;
@synthesize delegate = delegate_;
@synthesize topBarXIB;
@synthesize topBar = topBar_;
@synthesize topBarPosition;

- (id)initWithControllers:(NSArray *)controllers{
  self = [super initWithNibName:nil bundle:nil];
  if (self) {
    viewControllers_ = [controllers retain];
    selectedIndex_ = -1;
    self.topBarXIB = @"RMTopBarView";
    topBarPosition = RMTopBarPositionTop;
  }
  return self;
}

- (void)loadView{
  [super loadView];

  self.view.autoresizesSubviews = YES;
  self.view.autoresizingMask=UIViewAutoresizingFlexibleHeight;

  if (nil != self.parentViewController) {

    if ([self.parentViewController isKindOfClass:[UINavigationController class]]) {
      CGRect frame;
      if (![[(UINavigationController *)self.parentViewController navigationBar] isHidden]) {

        float height = self.parentViewController.view.frame.size.height;
        UINavigationBar *navBar = [(UINavigationController *)self.parentViewController navigationBar];

        height -= navBar.frame.size.height;
        height -= 20.0;
        frame =
        (CGRect){self.parentViewController.view.frame.origin,
          {self.parentViewController.view.frame.size.width, height}};
      }
      else frame = self.parentViewController.view.frame;
      [self.view setFrame:frame];
    }

  }

  [self.view setBackgroundColor:[UIColor whiteColor]];

}

- (void)didReceiveMemoryWarning
{
  // Releases the view if it doesn't have a superview.
  [super didReceiveMemoryWarning];

  // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

// Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
- (void)viewDidLoad{
  [super viewDidLoad];

  [self setupTopBar];
  [self positionTopBar];

  /*
   it is important to call - (void)setupContainerView after - (void)setupTopBar
   in order to calculate the actual size of the container
   */
  [self setupContainerView];

  [self selectControllerAtIndex:0 programmatically:YES];

}

#pragma mark compontents init
- (void)setupTopBar{
  if (!topBar_) {
    topBar_ = [[RMTopBar topBarWithXIB:self.topBarXIB] retain];
    [topBar_ setDelegate:self];
    [topBar_ setSelectedItemIndex:selectedIndex_];
  }
  [topBar_ removeFromSuperview];
  [self.view addSubview:topBar_];
}

- (void)positionTopBar{
  CGPoint position;

  if (RMTopBarPositionTop == topBarPosition) {
    position = CGPointMake(0.0, 0.0);
  }else{
    position = CGPointMake(0.0, self.view.frame.size.height - topBar_.frame.size.height);
  }

  [topBar_ setFrame:(CGRect){position, topBar_.frame.size}];
}

- (void)setupContainerView{
  CGRect containerFrame;

  if (RMTopBarPositionTop == topBarPosition) {
    containerFrame = CGRectMake(0.0,
                                topBar_.frame.size.height,
                                self.view.frame.size.width,
                                self.view.frame.size.height - topBar_.frame.size.height + 20
                                );

  }else{
    containerFrame = CGRectMake(0.0,
                                0.0,
                                self.view.frame.size.width,
                                self.view.frame.size.height - topBar_.frame.size.height
                                );
  }

  if (!containerView_) {
    containerView_ = [[UIView alloc] initWithFrame:containerFrame];
  }else{
    [containerView_ removeFromSuperview];
  }

  [containerView_ setBackgroundColor:[UIColor clearColor]];

  [self.view addSubview:containerView_];
}

#pragma mark Item Selection
- (void)setSelectedIndex:(NSInteger)selectedIndex{
  [self selectControllerAtIndex:selectedIndex programmatically:YES];
}

- (void)selectControllerAtIndex:(NSUInteger)index programmatically:(BOOL) program{

  if (index == selectedIndex_ && RMTopBarPositionBottom == topBarPosition && !program) {
    if ([currentController_ respondsToSelector:@selector(popToRootViewControllerAnimated:)]) {

      [currentController_ performSelector:@selector(popToRootViewControllerAnimated:)
                               withObject:[NSNumber numberWithBool:YES]];

    }else
      [currentController_.navigationController popToRootViewControllerAnimated:YES];
  }
  else{
    UIView *oldView = currentController_.view;
    selectedIndex_ = index;

    currentController_ = [viewControllers_ objectAtIndex:index];

    @try {
      [currentController_ setValue:self forKey:@"_parentViewController"];
    }
    @catch (NSException *exception) {
      DLog(@"Error : The _parentViewController couldn't be set! You may have a problem");
    }
    @finally {

    }

    UIView *newView = currentController_.view;

    //animate or not
    [oldView removeFromSuperview];

    [currentController_ viewWillAppear:NO];
    [containerView_ addSubview:newView];

    //executed after the view is displayed
    [currentController_ performSelector:@selector(viewDidAppear:)
                             withObject:nil
                             afterDelay:0.0];

    [self.view bringSubviewToFront:topBar_];
  }

  if (program) {
    [topBar_ setSelectedItemIndex:index];
    return;
  }

  if ([delegate_ respondsToSelector:@selector(rmTopBarController:didSelectController:atIndex:)]) {
    [delegate_ rmTopBarController:self
              didSelectController:currentController_
                          atIndex:selectedIndex_];
  }
}

#pragma mark RMTopBarDelegate
- (void)rmTopBar:(RMTopBar *)topBar didSelectItemAtIndex:(NSUInteger)index{
  [self selectControllerAtIndex:index programmatically:NO];
}

- (BOOL) rmTopBar:(RMTopBar *)topBar shouldSelectItemAtIndex:(NSUInteger) index{
  if ([delegate_ respondsToSelector:@selector(rmTopBarController:shouldSelectViewController:)]) {
    BOOL display = [delegate_ rmTopBarController:self shouldSelectViewController:index];
    return display;
  }
  return YES;
}

#pragma mark UIViewController forward methods

- (void) viewWillAppear:(BOOL)animated{
  [super viewWillAppear:animated];
  [currentController_ viewWillAppear:animated];
}

- (void) viewDidAppear:(BOOL)animated{
  [super viewDidAppear:animated];
  [currentController_ viewDidAppear:animated];
}

- (void)viewDidUnload{
  [topBar_ release]; topBar_ = nil;
  [containerView_ release]; containerView_ = nil;

  [super viewDidUnload];
}

- (void)dealloc{
  [topBarXIB release];
  [viewControllers_ release];
  [containerView_ release];
  [topBar_ release];
  [super dealloc];
}
@end