text:
var testCase = require('nodeunit').testCase;
var radius = require('../lib/radius');
var fs = require('fs');
var crypto = require('crypto');

var secret;

var test_args = {};

module.exports = testCase({
  setUp: function(callback) {
    secret = "nearbuy";
    callback();
  },
  tearDown: function(callback) {
    radius.unload_dictionaries();
    callback();
  },

  test_decode_mac_auth: function(test) {
    var raw_packet = fs.readFileSync(__dirname + '/captures/aruba_mac_auth.packet');

    radius.load_dictionary(__dirname + '/dictionaries/dictionary.aruba');

    var decoded = radius.decode({ packet: raw_packet, secret: secret });

    test.equal( decoded.code, 'Access-Request' );
    test.equal( decoded.identifier, 58 );
    test.equal( decoded.length, 208 );

    var expected_attrs = {
      'NAS-IP-Address': '10.0.0.90',
      'NAS-Port': 0,
      'NAS-Port-Type': 'Wireless-802.11',
      'User-Name': '7c:c5:37:ff:f8:af',
      'User-Password': '7c:c5:37:ff:f8:af',
      'Calling-Station-Id': '7CC537FFF8AF',
      'Called-Station-Id': '000B86F02068',
      'Service-Type': 'Login-User',
      'Vendor-Specific': {
        'Aruba-Essid-Name': 'muir-aruba-guest',
        'Aruba-Location-Id': '00:1a:1e:c6:b0:ca',
        'Aruba-AP-Group': 'cloud-cp'
      },
      'Message-Authenticator': new Buffer('f8a12329c7ed5a6e2568515243efb918', 'hex')
    };
    test.deepEqual( decoded.attributes, expected_attrs );

    test.done();
  },

  test_decode_mac_auth_without_secret: function(test) {
    var raw_packet = fs.readFileSync(__dirname + '/captures/aruba_mac_auth.packet');

    radius.load_dictionary(__dirname + '/dictionaries/dictionary.aruba');

    var decoded = radius.decode_without_secret({ packet: raw_packet });

    test.equal( decoded.code, 'Access-Request' );
    test.equal( decoded.identifier, 58 );
    test.equal( decoded.length, 208 );

    var expected_attrs = {
      'NAS-IP-Address': '10.0.0.90',
      'NAS-Port': 0,
      'NAS-Port-Type': 'Wireless-802.11',
      'User-Name': '7c:c5:37:ff:f8:af',
      'User-Password': null, // this is an encrypted field, and so cannot be read without the password
      'Calling-Station-Id': '7CC537FFF8AF',
      'Called-Station-Id': '000B86F02068',
      'Service-Type': 'Login-User',
      'Vendor-Specific': {
        'Aruba-Essid-Name': 'muir-aruba-guest',
        'Aruba-Location-Id': '00:1a:1e:c6:b0:ca',
        'Aruba-AP-Group': 'cloud-cp'
      },
      'Message-Authenticator': new Buffer('f8a12329c7ed5a6e2568515243efb918', 'hex')
    };
    test.deepEqual( decoded.attributes, expected_attrs );

    decoded = radius.decode({
      secret: secret,
      packet: radius.encode({
        secret: secret,
        code: "Access-Request",
        attributes: {
          'User-Name': 'Caenogaean-asphyxia',
          'User-Password': 'barratry-Wertherism'
        }
      })
    });

    test.equal( decoded.attributes['User-Password'], 'barratry-Wertherism' );

    test.done();
  },

  // make sure everthing is fine with no dictionaries
  test_decode_no_dicts: function(test) {
    var raw_packet = fs.readFileSync(__dirname + '/captures/aruba_mac_auth.packet');

    radius.unload_dictionaries();
    var orig_load = radius.load_dictionary;
    radius.load_dictionary = function() { };

    var decoded = radius.decode({ packet: raw_packet, secret: secret });

    test.equal( decoded.code, 'Access-Request' );
    test.equal( decoded.identifier, 58 );
    test.equal( decoded.length, 208 );

    // no pretty attributes
    test.deepEqual( decoded.attributes, {} );

    var expected_raw_attrs = [
      [4, new Buffer([10, 0, 0, 90])],
      [5, new Buffer([0, 0, 0, 0])],
      [61, new Buffer([0, 0, 0, 19])],
      [1, new Buffer('7c:c5:37:ff:f8:af')],
      [2, new Buffer('eb2ef7e83ec1a05e04fb5c6d91e088569a990fa2b1b2dc6a0f048596081164cd', 'hex')],
      [31, new Buffer('7CC537FFF8AF')],
      [30, new Buffer('000B86F02068')],
      [6, new Buffer([0, 0, 0, 1])],
      [26, new Buffer('000039e705126d7569722d61727562612d6775657374', 'hex')],
      [26, new Buffer('000039e7061330303a31613a31653a63363a62303a6361', 'hex')],
      [26, new Buffer('000039e70a0a636c6f75642d6370', 'hex')],
      [80, new Buffer('f8a12329c7ed5a6e2568515243efb918', 'hex')]
    ];

    test.deepEqual( decoded.raw_attributes, expected_raw_attrs );

    radius.load_dictionary = orig_load;

    test.done();
  },

  // can make a "naked" packet
  test_encode_access_request: function(test) {
    radius.load_dictionary(__dirname + '/dictionaries/dictionary.aruba');

    var attributes = [
      ['User-Name', 'ornithopter-aliptic'],
      ['User-Password', 'nucleohistone-overwilily'],
      ['Service-Type', 'Login-User'],
      ['NAS-IP-Address', '169.134.68.136'],

      ['Vendor-Specific', 14823, [
        ['Aruba-User-Role', 'cracked-tylote'],
        [2, 825]
      ]],
      ['Vendor-Specific', 14823, [['Aruba-Essid-Name', 'phene-dentinalgia']]]
    ];
    var packet = radius.encode({
      code: 'Access-Request',
      identifier: 123,
      attributes: attributes,
      secret: secret
    });

    var decoded = radius.decode({ packet: packet, secret: secret });
    test.equal( decoded.code, 'Access-Request' );
    test.equal( decoded.identifier, 123 );

    var expected_attrs = {
      'User-Name': 'ornithopter-aliptic',
      'User-Password': 'nucleohistone-overwilily',
      'Service-Type': 'Login-User',
      'NAS-IP-Address': '169.134.68.136',
      'Vendor-Specific': {
        'Aruba-User-Role': 'cracked-tylote',
        'Aruba-User-Vlan': 825,
        'Aruba-Essid-Name': 'phene-dentinalgia'
      }
    };
    test.deepEqual( decoded.attributes, expected_attrs );

    test.done();
  },

  test_decode_hash_attributes: function(test) {
    var attrs = {
      'User-Name': 'ornithopter-aliptic',
      'User-Password': 'nucleohistone-overwilily',
      'Service-Type': 'Login-User',
      'NAS-IP-Address': '169.134.68.136'
    };
    var packet = radius.encode({
      code: 'Access-Request',
      identifier: 123,
      attributes: attrs,
      secret: secret
    });

    var decoded = radius.decode({ packet: packet, secret: secret });
    test.equal( decoded.code, 'Access-Request' );
    test.equal( decoded.identifier, 123 );
    test.deepEqual( decoded.attributes, attrs );

    test.done();
  },

  test_throws_on_nested_hash_attributes: function(test) {
    var attrs = {
      'User-Name': 'ornithopter-aliptic',
      'User-Password': 'nucleohistone-overwilily',
      'Service-Type': 'Login-User',
      'NAS-IP-Address': '169.134.68.136',
      'Vendor-Specific': {
        'Aruba-User-Role': 'cracked-tylote',
        'Aruba-User-Vlan': 825,
        'Aruba-Essid-Name': 'phene-dentinalgia'
      }
    };

    test.throws(function() {
      var packet = radius.encode({
        code: 'Access-Request',
        identifier: 123,
        attributes: attrs,
        secret: secret
      });
    });
    test.done();
  },

  // test that our encoded packet matches bit-for-bit with a "real"
  // RADIUS packet
  test_encode_bit_for_bit: function(test) {
    var raw_packet = fs.readFileSync(__dirname + '/captures/aruba_mac_auth.packet');

    radius.load_dictionary(__dirname + '/dictionaries/dictionary.aruba');

    var encoded = radius.encode({
      code: 'Access-Request',
      identifier: 58,
      authenticator: new Buffer('4a45fae086d9e114286b37b5f371ec6c', 'hex'),
      attributes: [
        ['NAS-IP-Address', '10.0.0.90'],
        ['NAS-Port', 0],
        ['NAS-Port-Type', 'Wireless-802.11'],
        ['User-Name', '7c:c5:37:ff:f8:af'],
        ['User-Password', '7c:c5:37:ff:f8:af'],
        ['Calling-Station-Id', '7CC537FFF8AF'],
        ['Called-Station-Id', '000B86F02068'],
        ['Service-Type', 'Login-User'],
        ['Vendor-Specific', 14823, [['Aruba-Essid-Name', 'muir-aruba-guest']]],
        ['Vendor-Specific', 14823, [['Aruba-Location-Id', '00:1a:1e:c6:b0:ca']]],
        ['Vendor-Specific', 14823, [['Aruba-AP-Group', 'cloud-cp']]]
      ],
      secret: secret,
      add_message_authenticator: true
    });

    test.equal( encoded.toString('hex'), raw_packet.toString('hex') );

    test.done();
  },

  // encode will choose a random identifier for you if you don't provide one
  test_encode_random_identifer: function(test) {
    var decoded = radius.decode({
      packet: radius.encode({
        code: 'Access-Request',
        secret: secret
      }),
      secret: secret
    });
    test.ok( decoded.identifier >= 0 && decoded.identifier < 256 );

    var starting_id = decoded.identifier;

    // if you are unlucky this is an infinite loop
    while (true) {
      decoded = radius.decode({
        packet: radius.encode({
          code: 'Access-Request',
          secret: secret
        }),
        secret: secret
      });
      if (decoded.identifier != starting_id)
        break;
    }

    test.ok( true );

    test.done();
  },

  // given a previously decoded packet, prepare a response packet
  test_packet_response: function(test) {
    var raw_packet = fs.readFileSync(__dirname + '/captures/cisco_mac_auth.packet');

    var decoded = radius.decode({ packet: raw_packet, secret: secret });

    var response = radius.encode_response({
      packet: decoded,
      code: 'Access-Reject',
      secret: secret
    });

    var raw_response = fs.readFileSync(__dirname + '/captures/cisco_mac_auth_reject.packet');
    test.equal( response.toString('hex'), raw_response.toString('hex') );

    test.done();
  },

  // response needs to include proxy state
  test_response_include_proxy_state: function(test) {
    var request_with_proxy = radius.decode({
      packet: radius.encode({
        code: 'Access-Request',
        secret: secret,
        attributes: [
          ['User-Name', 'ascribe-despairer'],
          ['Proxy-State', new Buffer('womanhouse-Pseudotsuga')],
          ['User-Password', 'ridiculous'],
          ['Proxy-State', new Buffer('regretfully-unstability')]
        ]
      }),
      secret: secret
    });

    var decoded_response = radius.decode({
      packet: radius.encode_response({
        packet: request_with_proxy,
        code: 'Access-Reject',
        secret: secret
      }),
      secret: secret
    });

    var expected_raw_attributes = [
      [radius.attr_name_to_id('Proxy-State'), new Buffer('womanhouse-Pseudotsuga')],
      [radius.attr_name_to_id('Proxy-State'), new Buffer('regretfully-unstability')]
    ];

    test.deepEqual( decoded_response.raw_attributes, expected_raw_attributes );

    test.done();
  },

  // dont accidentally strip null bytes when encoding
  test_password_encode: function(test) {
    var decoded = radius.decode({
      packet: radius.encode({
        code: 'Access-Request',
        authenticator: new Buffer('426edca213c1bf6e005e90a64105ca3a', 'hex'),
        attributes: [['User-Password', 'ridiculous']],
        secret: secret
      }),
      secret: secret
    });

    test.equal( decoded.attributes['User-Password'], 'ridiculous' );

    test.done();
  },

  accounting_group: {
    setUp: function(cb) {
      radius.load_dictionary(__dirname + '/dictionaries/dictionary.airespace');

      test_args = {};
      test_args.raw_acct_request = fs.readFileSync(__dirname + '/captures/cisco_accounting.packet');
      test_args.expected_acct_attrs = {
        'User-Name': 'user_7C:C5:37:FF:F8:AF_134',
	      'NAS-Port': 1,
	      'NAS-IP-Address': '10.0.3.4',
        'Framed-IP-Address': '10.2.0.252',
        'NAS-Identifier': 'Cisco 4400 (Anchor)',
        'Vendor-Specific': {
          'Airespace-Wlan-Id': 2
        },
        'Acct-Session-Id': '4fecc41e/7c:c5:37:ff:f8:af/9',
        'Acct-Authentic': 'RADIUS',
        'Tunnel-Type': [0x00, 'VLAN'],
        'Tunnel-Medium-Type': [0x00, 'IEEE-802'],
        'Tunnel-Private-Group-Id': 5,
        'Acct-Status-Type': 'Start',
        'Calling-Station-Id': '7c:c5:37:ff:f8:af',
        'Called-Station-Id': '00:22:55:90:39:60'
      };
      cb();
    },

    test_accounting: function(test) {
      var raw_acct_request = test_args.raw_acct_request;
      var decoded = radius.decode({ packet: raw_acct_request, secret: secret });

      var expected_attrs = test_args.expected_acct_attrs;

      test.deepEqual( decoded.attributes, expected_attrs );

      // test we can encode the same packet
      var encoded = radius.encode({
        code: 'Accounting-Request',
        identifier: decoded.identifier,
        secret: secret,
        attributes: [
       	  ['User-Name', 'user_7C:C5:37:FF:F8:AF_134'],
	        ['NAS-Port', 1],
	        ['NAS-IP-Address', '10.0.3.4'],
          ['Framed-IP-Address', '10.2.0.252'],
          ['NAS-Identifier', 'Cisco 4400 (Anchor)'],
          ['Vendor-Specific', 'Airespace', [['Airespace-Wlan-Id', 2]]],
          ['Acct-Session-Id', '4fecc41e/7c:c5:37:ff:f8:af/9'],
          ['Acct-Authentic', 'RADIUS'],
          ['Tunnel-Type', 0x00, 'VLAN'],
          ['Tunnel-Medium-Type', 0x00, 'IEEE-802'],
          ['Tunnel-Private-Group-Id', '5'],
          ['Acct-Status-Type', 'Start'],
          ['Calling-Station-Id', '7c:c5:37:ff:f8:af'],
          ['Called-Station-Id', '00:22:55:90:39:60']
        ]
      });
      test.equal( encoded.toString('hex'), raw_acct_request.toString('hex') );

      var raw_acct_response = fs.readFileSync(__dirname +
                                              '/captures/cisco_accounting_response.packet');
      encoded = radius.encode_response({
        packet: decoded,
        secret: secret,
        code: 'Accounting-Response'
      });
      test.equal( encoded.toString('hex'), raw_acct_response.toString('hex') );

      test.done();
    },

    test_invalid_accounting_packet_authenticator: function(test) {
      var raw_acct_request = test_args.raw_acct_request;
      var expected_attrs = test_args.expected_acct_attrs;

      // detect invalid accounting packets
      test.throws( function() {
        radius.decode({ packet: raw_acct_request, secret: 'not-secret' });
      } );

      try {
        radius.decode({ packet: raw_acct_request, secret: 'not-secret' });
      } catch (err) {
        test.deepEqual( err.decoded.attributes, expected_attrs );
      }
      test.done();
    }
  },

  test_no_empty_strings: function(test) {
    var decoded = radius.decode({
      secret: secret,
      packet: radius.encode({
        code: 'Access-Request',
        attributes: [['User-Name', '']],
        secret: secret
      })
    });

    // don't send empty strings (see RFC2865)
    test.deepEqual( decoded.attributes, {} );

    test.done();
  },

  test_repeated_attribute: function(test) {
    var decoded = radius.decode({
      secret: secret,
      packet: radius.encode({
        secret: secret,
        code: 'Access-Reject',
        attributes: [
          ['Reply-Message', 'message one'],
          ['Reply-Message', 'message two']
        ]
      })
    });

    var expected_attrs = {
      'Reply-Message': ['message one', 'message two']
    };
    test.deepEqual( decoded.attributes, expected_attrs );

    test.done();
  },

  test_dictionary_include: function(test) {
    radius.unload_dictionaries();
    radius.add_dictionary(__dirname + '/dictionaries/dictionary.test1');

    var decoded = radius.decode({
      secret: secret,
      packet: radius.encode({
        secret: secret,
        code: 'Access-Request',
        attributes: [['Attribute-Test1', 'foo'], ['Attribute-Test2', 'bar']]
      })
    });

    var expected_attrs = {
      'Attribute-Test1': 'foo',
      'Attribute-Test2': 'bar'
    };
    test.deepEqual( decoded.attributes, expected_attrs );

    test.done();
  },

  // make sure we can load the dicts in any order
  test_dictionary_out_of_order: function(test) {
    var dicts = fs.readdirSync(__dirname + '/../dictionaries');

    // make sure we can load any dictionary first
    for (var i = 0; i < dicts.length; i++) {
      radius.unload_dictionaries();
      radius.load_dictionary(__dirname + '/../dictionaries/' + dicts[i]);
    }

    // and spot check things actually work loaded out of order
    radius.unload_dictionaries();
    radius.load_dictionary(__dirname + '/../dictionaries/dictionary.rfc2867');
    radius.load_dictionary(__dirname + '/../dictionaries/dictionary.rfc2866');

    var decoded = radius.decode({
      secret: secret,
      packet: radius.encode({
        code: 'Accounting-Request',
        secret: secret,
        attributes: [
          ['Acct-Status-Type', 'Tunnel-Reject']
        ]
      })
    });

    test.equal( decoded.attributes['Acct-Status-Type'], 'Tunnel-Reject' );

    radius.unload_dictionaries();
    radius.load_dictionary(__dirname + '/dictionaries/dictionary.test_tunnel_type');
    radius.load_dictionaries();

    decoded = radius.decode({
      secret: secret,
      packet: radius.encode({
        code: 'Accounting-Request',
        secret: secret,
        attributes: [
          ['Tunnel-Type', 0x00, 'TESTTUNNEL']
        ]
      })
    });

    var expected_attrs = {'Tunnel-Type': [0x00, 'TESTTUNNEL']};
    test.deepEqual( decoded.attributes, expected_attrs );

    test.done();
  },

  test_zero_identifer: function(test) {
    var decoded = radius.decode({
      packet: radius.encode({
        secret: secret,
        code: 'Access-Request',
        identifier: 0
      }),
      secret: secret
    });

    test.equal( decoded.identifier, 0 );
    test.done();
  },

  test_date_type: function(test) {
    var raw_packet = fs.readFileSync(__dirname + '/captures/motorola_accounting.packet');

    var decoded = radius.decode({
      packet: raw_packet,
      secret: secret
    });

    var epoch = 1349879753;

    test.equal( decoded.attributes['Event-Timestamp'].getTime(), epoch * 1000 );

    var encoded = radius.encode({
      code: 'Accounting-Request',
      identifier: decoded.identifier,
      attributes: [
        ['User-Name', '00-1F-3B-8C-3A-15'],
        ['Acct-Status-Type', 'Start'],
        ['Acct-Session-Id', '1970D5A4-001F3B8C3A15-0000000001'],
        ['Calling-Station-Id', '00-1F-3B-8C-3A-15'],
        ['Called-Station-Id', 'B4-C7-99-77-59-D0:muir-moto-guest-site1'],
        ['NAS-Port', 1],
        ['NAS-Port-Type', 'Wireless-802.11'],
        ['NAS-IP-Address', '10.2.0.3'],
        ['NAS-Identifier', 'ap6532-70D5A4'],
        ['NAS-Port-Id', 'radio2'],
        ['Event-Timestamp', new Date(epoch * 1000)],
        ['Tunnel-Type', 0x00, 'VLAN' ],
        ['Tunnel-Medium-Type', 0x00, 'IEEE-802'],
        ['Tunnel-Private-Group-Id', '30'],
        ['Acct-Authentic', 'RADIUS']
      ],
      secret: secret
    });

    test.equal( encoded.toString('hex'), raw_packet.toString('hex') );

    test.done();
  },

  test_date_type_non_mult_1000_ms: function(test) {
    var encoded;
    test.doesNotThrow(function() {
      encoded = radius.encode({
        code: 'Accounting-Request',
        identifier: 123,
        attributes: [
          ['Event-Timestamp', new Date(1403025894009)]
        ],
        secret: secret
      });
    });

    // truncates ms
    var decoded = radius.decode({ packet: encoded, secret: secret });
    test.equal( decoded.attributes['Event-Timestamp'].getTime(), 1403025894000 );

    test.done();
  },

  test_disconnect_request: function(test) {
    var encoded = radius.encode({
      code: 'Disconnect-Request',
      identifier: 54,
      secret: secret,
      attributes: [
        ['User-Name', 'mariticide-inquietation'],
        ['NAS-Identifier', 'Aglauros-charioted']
      ]
    });

    // check we did the non-user-password authenticator
    var got_authenticator = new Buffer(16);
    encoded.copy(got_authenticator, 0, 4);
    encoded.fill(0, 4, 20);

    var expected_authenticator = new Buffer(16);
    var hasher = crypto.createHash("md5");
    hasher.update(encoded);
    hasher.update(secret);
    expected_authenticator.write(hasher.digest("binary"), 0, 16, "binary");

    test.equal( got_authenticator.toString('hex'), expected_authenticator.toString('hex') );

    // and make sure we check the authenticator when decoding
    test.throws(function() {
      radius.decode({
        packet: encoded,
        secret: secret
      });
    });

    expected_authenticator.copy(encoded, 4, 0);
    test.doesNotThrow(function() {
      radius.decode({
        packet: encoded,
        secret: secret
      });
    });

    test.done();
  },

  test_verify_response: function(test) {
    var request = radius.encode({
      secret: secret,
      code: 'Accounting-Request',
      attributes: {
        'User-Name': '00-1F-3B-8C-3A-15',
        'Acct-Status-Type':  'Start'
      }
    });

    var response = radius.encode_response({
      secret: secret,
      code: 'Accounting-Response',
      packet: radius.decode({ packet: request, secret: secret })
    });

    test.ok( radius.verify_response({
      request: request,
      response: response,
      secret: secret
    }) );

    test.ok( !radius.verify_response({
      request: request,
      response: response,
      secret: "Calliopsis-misbeholden"
    }) );

    // response encoded with wrong secret
    response = radius.encode_response({
      secret: "moyenne-paraboliform",
      code: 'Accounting-Response',
      packet: radius.decode({ packet: request, secret: secret })
    });
    test.ok( !radius.verify_response({
      request: request,
      response: response,
      secret: secret
    }) );

    test.done();
  },

  test_server_request: function(test) {
    var encoded1 = radius.encode({
      code: 'Status-Server',
      identifier: 54,
      secret: secret,
      attributes: [
        ['NAS-Identifier', 'symphilism-dicentrine']
      ]
    });

    var encoded2 = radius.encode({
      code: 'Status-Server',
      identifier: 54,
      secret: secret,
      attributes: [
        ['NAS-Identifier', 'symphilism-dicentrine']
      ]
    });

    // check we are doing a random authenticator
    var got_authenticator1 = new Buffer(16);
    encoded1.copy(got_authenticator1, 0, 4);

    var got_authenticator2 = new Buffer(16);
    encoded2.copy(got_authenticator2, 0, 4);

    test.notEqual( got_authenticator1.toString(), got_authenticator2.toString() );

    var response = radius.encode_response({
      code: 'Access-Accept',
      secret: secret,
      packet: radius.decode({packet: encoded1, secret: secret})
    });

    test.ok( radius.verify_response({
      request: encoded1,
      response: response,
      secret: secret
    }) );

    test.done();
  },

  test_vendor_names_with_numbers: function(test) {
    radius.load_dictionary(__dirname + '/dictionaries/dictionary.number_vendor_name');

    var encoded = radius.encode({
      code: "Access-Request",
      secret: secret,

      attributes: [
        ['Vendor-Specific', '123Foo', [
          ['1Integer', 478],
          ['1String', 'Zollernia-fibrovasal'],
          ['12345', 'myrmecophagoid-harn']
        ]]
      ]
    });

    var decoded = radius.decode({
      packet: encoded,
      secret: secret
    });

    test.equal( radius.vendor_name_to_id('123Foo'), 995486 );

    test.deepEqual( decoded.attributes, {
      'Vendor-Specific': {
        '1Integer': 478,
        '1String': 'Zollernia-fibrovasal',
        '12345': 'myrmecophagoid-harn'
      }
    } );

    test.done();
  },

  message_authenticator_group: {
    setUp: function(cb) {
      secret = "testing123";

      test_args = {
        raw_request: fs.readFileSync(__dirname + '/captures/eap_request.packet')
      };
      test_args.parsed_request = radius.decode({
        packet: test_args.raw_request,
        secret: secret
      });
      cb();
    },

    // make sure we calculate the same Message-Authenticator
    test_calculate: function(test) {
      var attrs_without_ma = test_args.parsed_request.raw_attributes.filter(function(a) {
        return a[0] != radius.attr_name_to_id('Message-Authenticator');
      });

      var encoded = radius.encode({
        code: test_args.parsed_request.code,
        identifier: test_args.parsed_request.identifier,
        authenticator: test_args.parsed_request.authenticator,
        attributes: attrs_without_ma,
        secret: secret
      });

      test.equal( encoded.toString('hex'), test_args.raw_request.toString('hex') );

      test.done();
    },

    // encode_response should calculate the appropriate Message-Authenticator
    test_encode_response: function(test) {
      var response = radius.encode_response({
        code: "Access-Accept",
        secret: secret,
        packet: test_args.parsed_request
      });

      var parsed_response = radius.decode({
        packet: response,
        secret: secret
      });

      // calculate expected Message-Authenticator

      var empty = new Buffer(16);
      empty.fill(0);

      var expected_response = radius.encode({
        code: "Access-Accept",
        identifier: test_args.parsed_request.identifier,
        authenticator: test_args.parsed_request.authenticator,
        attributes: [["Message-Authenticator", empty]],
        secret: secret
      });

      // expected_response's authenticator is correct, but Message-Authenticator is wrong
      // (it's all 0s). make sure verify_response checks both
      test.ok( !radius.verify_response({
        request: test_args.raw_request,
        response: expected_response,
        secret: secret
      }) );

      // put back the request's authenticator
      test_args.parsed_request.authenticator.copy(expected_response, 4);

      var expected_ma = radius.calculate_message_authenticator(expected_response, secret);
      test.equal(
        parsed_response.attributes["Message-Authenticator"].toString("hex"),
        expected_ma.toString("hex")
      );

      test.ok( radius.verify_response({
        request: test_args.raw_request,
        response: response,
        secret: secret
      }) );

      test.done();
    },

    // response is missing Message-Authenticator, not okay
    test_response_missing_ma: function(test) {
      var bad_response = radius.encode({
        code: "Access-Accept",
        identifier: test_args.parsed_request.identifier,
        authenticator: test_args.parsed_request.authenticator,
        attributes: [],
        secret: secret
      });

      test.ok( !radius.verify_response({
        request: test_args.raw_request,
        response: bad_response,
        secret: secret
      }) );

      test.done();
    },

    // make sure we verify Message-Authenticator when decoding requests
    test_decode_verify: function(test) {
      test.throws(function() {
        radius.decode({
          packet: test_args.raw_request,
          secret: 'wrong secret'
        });
      });

      test.done();
    }
  },

  test_utf8_strings: function(test) {
    var encoded = radius.encode({
      secret: "密码",
      code: "Access-Request",
      attributes: {
        "User-Name": "金庸先生",
        "User-Password": "降龙十八掌"
      }
    });

    var decoded = radius.decode({
      packet: encoded,
      secret: "密码"
    });

    test.deepEqual( {
      "User-Name": "金庸先生",
      "User-Password": "降龙十八掌"
    }, decoded.attributes );

    test.done();
  }
});


text:
namespace ofxLaser {
class Dot : public Shape{

	public :

    Dot(const ofPoint& dotPosition, const ofColor& dotColour, float dotIntensity, string profilelabel);
    void appendPointsToVector(vector<ofxLaser::Point>& points, const RenderProfile& profile, float speedMultiplier);
    void addPreviewToMesh(ofMesh& mesh);
    virtual bool intersectsRect(ofRectangle & rect);

	float intensity = 1;
	int maxPoints = 5;

};

}

redpajama_set_name: RedPajamaGithub


text:
package hcsshim

import (
	"fmt"
	"syscall"

	"github.com/Microsoft/hcsshim/internal/hns"

	"github.com/Microsoft/hcsshim/internal/hcs"
	"github.com/Microsoft/hcsshim/internal/hcserror"
)

var (
	// ErrComputeSystemDoesNotExist is an error encountered when the container being operated on no longer exists = hcs.exist
	ErrComputeSystemDoesNotExist = hcs.ErrComputeSystemDoesNotExist

	// ErrElementNotFound is an error encountered when the object being referenced does not exist
	ErrElementNotFound = hcs.ErrElementNotFound

	// ErrElementNotFound is an error encountered when the object being referenced does not exist
	ErrNotSupported = hcs.ErrNotSupported

	// ErrInvalidData is an error encountered when the request being sent to hcs is invalid/unsupported
	// decimal -2147024883 / hex 0x8007000d
	ErrInvalidData = hcs.ErrInvalidData

	// ErrHandleClose is an error encountered when the handle generating the notification being waited on has been closed
	ErrHandleClose = hcs.ErrHandleClose

	// ErrAlreadyClosed is an error encountered when using a handle that has been closed by the Close method
	ErrAlreadyClosed = hcs.ErrAlreadyClosed

	// ErrInvalidNotificationType is an error encountered when an invalid notification type is used
	ErrInvalidNotificationType = hcs.ErrInvalidNotificationType

	// ErrInvalidProcessState is an error encountered when the process is not in a valid state for the requested operation
	ErrInvalidProcessState = hcs.ErrInvalidProcessState

	// ErrTimeout is an error encountered when waiting on a notification times out
	ErrTimeout = hcs.ErrTimeout

	// ErrUnexpectedContainerExit is the error encountered when a container exits while waiting for
	// a different expected notification
	ErrUnexpectedContainerExit = hcs.ErrUnexpectedContainerExit

	// ErrUnexpectedProcessAbort is the error encountered when communication with the compute service
	// is lost while waiting for a notification
	ErrUnexpectedProcessAbort = hcs.ErrUnexpectedProcessAbort

	// ErrUnexpectedValue is an error encountered when hcs returns an invalid value
	ErrUnexpectedValue = hcs.ErrUnexpectedValue

	// ErrVmcomputeAlreadyStopped is an error encountered when a shutdown or terminate request is made on a stopped container
	ErrVmcomputeAlreadyStopped = hcs.ErrVmcomputeAlreadyStopped

	// ErrVmcomputeOperationPending is an error encountered when the operation is being completed asynchronously
	ErrVmcomputeOperationPending = hcs.ErrVmcomputeOperationPending

	// ErrVmcomputeOperationInvalidState is an error encountered when the compute system is not in a valid state for the requested operation
	ErrVmcomputeOperationInvalidState = hcs.ErrVmcomputeOperationInvalidState

	// ErrProcNotFound is an error encountered when a procedure look up fails.
	ErrProcNotFound = hcs.ErrProcNotFound

	// ErrVmcomputeOperationAccessIsDenied is an error which can be encountered when enumerating compute systems in RS1/RS2
	// builds when the underlying silo might be in the process of terminating. HCS was fixed in RS3.
	ErrVmcomputeOperationAccessIsDenied = hcs.ErrVmcomputeOperationAccessIsDenied

	// ErrVmcomputeInvalidJSON is an error encountered when the compute system does not support/understand the messages sent by management
	ErrVmcomputeInvalidJSON = hcs.ErrVmcomputeInvalidJSON

	// ErrVmcomputeUnknownMessage is an error encountered guest compute system doesn't support the message
	ErrVmcomputeUnknownMessage = hcs.ErrVmcomputeUnknownMessage

	// ErrNotSupported is an error encountered when hcs doesn't support the request
	ErrPlatformNotSupported = hcs.ErrPlatformNotSupported
)

type EndpointNotFoundError = hns.EndpointNotFoundError
type NetworkNotFoundError = hns.NetworkNotFoundError

// ProcessError is an error encountered in HCS during an operation on a Process object
type ProcessError struct {
	Process   *process
	Operation string
	Err       error
	Events    []hcs.ErrorEvent
}

// ContainerError is an error encountered in HCS during an operation on a Container object
type ContainerError struct {
	Container *container
	Operation string
	Err       error
	Events    []hcs.ErrorEvent
}

func (e *ContainerError) Error() string {
	if e == nil {
		return "<nil>"
	}

	if e.Container == nil {
		return "unexpected nil container for error: " + e.Err.Error()
	}

	s := "container " + e.Container.system.ID()

	if e.Operation != "" {
		s += " encountered an error during " + e.Operation
	}

	switch e.Err.(type) {
	case nil:
		break
	case syscall.Errno:
		s += fmt.Sprintf(": failure in a Windows system call: %s (0x%x)", e.Err, hcserror.Win32FromError(e.Err))
	default:
		s += fmt.Sprintf(": %s", e.Err.Error())
	}

	for _, ev := range e.Events {
		s += "\n" + ev.String()
	}

	return s
}

func makeContainerError(container *container, operation string, extraInfo string, err error) error {
	// Don't double wrap errors
	if _, ok := err.(*ContainerError); ok {
		return err
	}
	containerError := &ContainerError{Container: container, Operation: operation, Err: err}
	return containerError
}

func (e *ProcessError) Error() string {
	if e == nil {
		return "<nil>"
	}

	if e.Process == nil {
		return "Unexpected nil process for error: " + e.Err.Error()
	}

	s := fmt.Sprintf("process %d in container %s", e.Process.p.Pid(), e.Process.p.SystemID())
	if e.Operation != "" {
		s += " encountered an error during " + e.Operation
	}

	switch e.Err.(type) {
	case nil:
		break
	case syscall.Errno:
		s += fmt.Sprintf(": failure in a Windows system call: %s (0x%x)", e.Err, hcserror.Win32FromError(e.Err))
	default:
		s += fmt.Sprintf(": %s", e.Err.Error())
	}

	for _, ev := range e.Events {
		s += "\n" + ev.String()
	}

	return s
}

func makeProcessError(process *process, operation string, extraInfo string, err error) error {
	// Don't double wrap errors
	if _, ok := err.(*ProcessError); ok {
		return err
	}
	processError := &ProcessError{Process: process, Operation: operation, Err: err}
	return processError
}

// IsNotExist checks if an error is caused by the Container or Process not existing.
// Note: Currently, ErrElementNotFound can mean that a Process has either
// already exited, or does not exist. Both IsAlreadyStopped and IsNotExist
// will currently return true when the error is ErrElementNotFound.
func IsNotExist(err error) bool {
	if _, ok := err.(EndpointNotFoundError); ok {
		return true
	}
	if _, ok := err.(NetworkNotFoundError); ok {
		return true
	}
	return hcs.IsNotExist(getInnerError(err))
}

// IsAlreadyClosed checks if an error is caused by the Container or Process having been
// already closed by a call to the Close() method.
func IsAlreadyClosed(err error) bool {
	return hcs.IsAlreadyClosed(getInnerError(err))
}

// IsPending returns a boolean indicating whether the error is that
// the requested operation is being completed in the background.
func IsPending(err error) bool {
	return hcs.IsPending(getInnerError(err))
}

// IsTimeout returns a boolean indicating whether the error is caused by
// a timeout waiting for the operation to complete.
func IsTimeout(err error) bool {
	return hcs.IsTimeout(getInnerError(err))
}

// IsAlreadyStopped returns a boolean indicating whether the error is caused by
// a Container or Process being already stopped.
// Note: Currently, ErrElementNotFound can mean that a Process has either
// already exited, or does not exist. Both IsAlreadyStopped and IsNotExist
// will currently return true when the error is ErrElementNotFound.
func IsAlreadyStopped(err error) bool {
	return hcs.IsAlreadyStopped(getInnerError(err))
}

// IsNotSupported returns a boolean indicating whether the error is caused by
// unsupported platform requests
// Note: Currently Unsupported platform requests can be mean either
// ErrVmcomputeInvalidJSON, ErrInvalidData, ErrNotSupported or ErrVmcomputeUnknownMessage
// is thrown from the Platform
func IsNotSupported(err error) bool {
	return hcs.IsNotSupported(getInnerError(err))
}

func getInnerError(err error) error {
	switch pe := err.(type) {
	case nil:
		return nil
	case *ContainerError:
		err = pe.Err
	case *ProcessError:
		err = pe.Err
	}
	return err
}

func convertSystemError(err error, c *container) error {
	if serr, ok := err.(*hcs.SystemError); ok {
		return &ContainerError{Container: c, Operation: serr.Op, Err: serr.Err, Events: serr.Events}
	}
	return err
}

func convertProcessError(err error, p *process) error {
	if perr, ok := err.(*hcs.ProcessError); ok {
		return &ProcessError{Process: p, Operation: perr.Op, Err: perr.Err, Events: perr.Events}
	}
	return err
}


text:
<!DOCTYPE html>

<meta charset="utf-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>PHPhisher - Scenarios</title>

<link rel="stylesheet" href="../css/bootstrap.css">

 Configuration 2/2

 Select one of the available scenarios and you are ready to go.

Office365

Use this

Dlink

Use this

Connection Reset

Use this

Router Admin Page

Use this

Facebook oAuth

Use this

Facebook Login

Use this

Google Login

Use this

Starbucks Login

Use this

Yahoo Login

Use this

PHPhisher is an open-source project made by NickTehPro


text:
<!doctype html>

	<meta charset="utf-8">
	<meta http-equiv="X-UA-Compatible" content="IE=edge">
	<title>Kartwars Bot</title>
	<meta name="description" content="">
	<meta name="viewport" content="width=device-width, initial-scale=1">
	<link rel="stylesheet" href="assets/css/main.css">

						Search
						<input id="tsd-search-field" type="text" />

Preparing search index...

The search index is not available

					Kartwars Bot

						Options

								All

Public

Public/Protected

All

							<input type="checkbox" id="tsd-filter-inherited" checked />
							Inherited
							<input type="checkbox" id="tsd-filter-externals" checked />
							Externals
							<input type="checkbox" id="tsd-filter-only-exported" />
							Only exported

					Menu

					Globals

 Kartwars Bot

Kartwars.io Bot Championship Edition

aka "Intelligent self-control and fighting system of karts in the Kartwars.io multiplayer game".

Welcome to the kartwars.io bot!

Table of Contents

Goals

Features

Installation instructions

Hotkeys

Directory Contents

Thanks

Goals

No global pollution

Easy to use

Easy to create and embed any strategy and tactic

Clean and well structured source code

Features

Easy installable

Easy customizable

Unlock all skins

Multiple tactics

Strong documentation

Visual debugging

Real time customization through dat.GUI

Installation instructions

If you are on chrome, download the TamperMonkey extension.

On other browsers, use the GreaseMonkey extension.

Once installed, click on this, and choose Install.

Go to kartwars.io, and enjoy !

Hotkeys

							Key
							Result

							Ctrl + B
							Toggle Bot enabled/disabled

							Mouse wheel
							Zoom in/out

Directory Contents

├── build                         # Compiled source code.
├── doc                           # Generated documentation.
└── src                           # Source files.
    └── DracoolaArt.Bot.Kartwars  # Main VS project.
        ├── lib                   # Bot source code.
        └── bot.user.js           # Injection script.

Thanks

The following libraries / open-source projects were used in the development of Kartwars Bot:

dat.GUI

less

TypeScript

typedoc

node.js

						Globals

						Internals

						"victor"

						Externals

						Dracoola<wbr>Art

						Reverse<wbr>Engineering

						Victor

						Victor<wbr>Coordinates

Legend

Module

Object literal

Variable

Function

Function with type parameter

Index signature

Type alias

Enumeration

Enumeration member

Property

Method

Interface

Interface with type parameter

Constructor

Property

Method

Index signature

Class

Class with type parameter

Constructor

Property

Method

Accessor

Index signature

Inherited constructor

Inherited property

Inherited method

Inherited accessor

Protected property

Protected method

Protected accessor

Private property

Private method

Private accessor

Static property

Static method

Generated using TypeDoc


text:
package org.metaborg.spoofax.shell.client.console.impl;

import static org.metaborg.spoofax.shell.client.console.AnsiColors.findClosest;

import java.awt.Color;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintStream;
import java.io.PrintWriter;
import java.nio.charset.Charset;
import java.util.ArrayList;
import java.util.function.Consumer;
import java.util.function.Function;
import java.util.stream.Collectors;

import org.fusesource.jansi.Ansi;
import org.metaborg.core.style.IStyle;
import org.metaborg.spoofax.shell.client.IDisplay;
import org.metaborg.spoofax.shell.client.IInputHistory;
import org.metaborg.spoofax.shell.output.StyledText;

import com.google.inject.Inject;
import com.google.inject.name.Named;

import jline.console.ConsoleReader;

/**
 * A terminal UI, offering a way of entering input and implementing {@link IDisplay} to
 * display results.
 */
public class TerminalUserInterface implements IDisplay {
    private final ConsoleReader reader;
    private final ArrayList<String> lines;
    private final PrintWriter out;
    private final PrintWriter err;
    private final IInputHistory hist;
    private StyledText prompt;
    private StyledText continuationPrompt;

    /**
     * @param reader
     *            The JLine2 {@link ConsoleReader} used to get input.
     * @param out
     *            The {@link PrintStream} to write results to.
     * @param err
     *            The {@link PrintStream} to write errors to.
     * @param hist
     *            The input history adapter for JLine2.
     */
    @Inject
    public TerminalUserInterface(ConsoleReader reader, @Named("out") OutputStream out,
                                 @Named("err") OutputStream err, IInputHistory hist) {
        this.reader = reader;
        this.hist = hist;
        reader.setExpandEvents(false);
        reader.setHandleUserInterrupt(true);
        reader.setBellEnabled(true);
        this.out =
            new PrintWriter(new BufferedWriter(new OutputStreamWriter(out,
                                                                      Charset.forName("UTF-8"))));
        this.err =
            new PrintWriter(new BufferedWriter(new OutputStreamWriter(err,
                                                                      Charset.forName("UTF-8"))));

        lines = new ArrayList<>();

        this.setPrompt(new StyledText(Color.GREEN, "[In ]: "));
        this.setContinuationPrompt(new StyledText("[...]: "));
    }

    /**
     * Save this line as the end of the multiline input.
     *
     * @param lastLine
     *            The line to save.
     */
    protected void saveLine(String lastLine) {
        lines.add(lastLine);
    }

    /**
     * Set the prompt to display.
     *
     * @param promptString
     *            The prompt string.
     */
    public void setPrompt(StyledText promptString) {
        prompt = promptString;
    }

    /**
     * Set the prompt to display when in multiline mode.
     *
     * @param promptString
     *            The prompt string.
     */
    public void setContinuationPrompt(StyledText promptString) {
        continuationPrompt = promptString;
    }

    /**
     * Get input from the user. This method blocks until the user presses the Return key.
     *
     * @return The input as typed by the user, or {@code null} in case of an exception.
     */
    public String getInput() {
        String input = null;
        String lastLine;
        reader.setPrompt(ansi(prompt));
        try {
            // While the input is not empty, keep asking.
            while ((lastLine = reader.readLine()) != null && lastLine.trim().length() > 0) {
                reader.flush();
                reader.setPrompt(ansi(continuationPrompt));
                saveLine(lastLine);
            }
            // Concatenate the strings with newlines in between.
            input = lastLine == null ? null : lines.stream().collect(Collectors.joining("\n"));
            // Clear the lines for next input.
            lines.clear();
        } catch (IOException e) {
            err.println("An error occured: " + e.getMessage() + "\nExiting...");
            err.flush();
        }
        return input;
    }

    /**
     * Return the {@link IInputHistory} kept by this user interface.
     *
     * @return The {@link IInputHistory} implementation.
     */
    public IInputHistory history() {
        return hist;
    }

    @Override
    public void displayStyledText(StyledText text) {
        out.println(ansi(text));
        out.flush();
    }

    private <T> void optional(T t, Function<T, Boolean> check, Consumer<T> accept) {
        if (check.apply(t)) {
            accept.accept(t);
        }
    }

    private String ansi(StyledText styled) {
        Ansi ansi = Ansi.ansi();
        styled.getSource().forEach(e -> {
            if (e.style() != null) {
                IStyle style = e.style();
                optional(style.color(),           (c) -> c != null, (c) -> ansi.fg(findClosest(c)));
                optional(style.backgroundColor(), (c) -> c != null, (c) -> ansi.bg(findClosest(c)));
                optional(style.bold(),           (c) -> c, (c) -> ansi.bold());
                optional(style.italic(),         (c) -> c, (c) -> ansi.a(Ansi.Attribute.ITALIC));
                optional(style.underscore(),     (c) -> c, (c) -> ansi.a(Ansi.Attribute.UNDERLINE));
                ansi.a(e.fragment()).reset();
            } else {
                ansi.a(e.fragment());
            }
        });
        return ansi.toString();
    }
}


text:
<?xml version="1.0"?>
<config>
  <modules>
    <Bugsnag_Notifier>
      <active>true</active>
      <codePool>community</codePool>
    </Bugsnag_Notifier>
  </modules>
</config>


text:
typedef int          AMI_merge_flag;
typedef unsigned int arity_t;

static inline void
makeName (char *prepre, char *pre, int id, char *dest)
{
   char tmparray[5];

   strcpy (dest, prepre);
   strcat (dest, pre);
   sprintf (tmparray, "%d", id);
   strcat (dest, tmparray);
}

// **************************************************************************
// *                                                                        *
// *   A M I _ s i n g l e _ m e r g e _ d h                                *
// *                                                                        *
// * This is a common merge routine for all of the AMI_merge, AMI_ptr_merge *
// * and AMI_key_merge entry points. It is also used by the sort entry      *
// * points AMI_sort, AMI_ptr_sort and AMI_key_sort and by the routine      *
// * AMI_partition_and_merge.  Differences are encapsulated within the      *
// * merge heap object 'MergeHeap'. It is assumed that MergeHeap.allocate   *
// * was called before entering AMI_single_merge_dh.                        *
// *                                                                        *
// **************************************************************************

template < class T, class M >
    AMI_err
AMI_single_merge_dh (AMI_STREAM < T > **inStreams, arity_t arity,
		     AMI_STREAM < T > *outStream,  M MergeHeap  )
{

   unsigned int i;
   AMI_err ami_err;

   //Pointers to current leading elements of streams
   T** in_objects = new T*[arity + 1];

   // **************************************************************
   // * Rewind each input stream and read its first element.       *
   // **************************************************************

   for (i = 0; i < arity; i++) {

      if ((ami_err = inStreams[i]->seek (0)) != AMI_ERROR_NO_ERROR) {
	  delete[] in_objects;
	  return ami_err;
      }

      if ((ami_err = inStreams[i]->read_item (&(in_objects[i]))) !=
	  AMI_ERROR_NO_ERROR) {
	 if (ami_err == AMI_ERROR_END_OF_STREAM) {
	    in_objects[i] = NULL;
	 } else {
	     delete[] in_objects;
	     return ami_err;
	 }
      } else {
        MergeHeap.insert( in_objects[i], i );
      }
   }

   // *********************************************************
   // * Build a heap from the smallest items of each stream   *
   // *********************************************************

   MergeHeap.initialize ( );

   // *********************************************************
   // * Perform the merge until the inputs are exhausted.     *
   // *********************************************************
   while (MergeHeap.sizeofheap ()) {

      i = MergeHeap.get_min_run_id ();

      if ((ami_err = outStream->write_item (*in_objects[i]))
	  != AMI_ERROR_NO_ERROR) {
	  delete[] in_objects;
	  return ami_err;
      }

      if ((ami_err = inStreams[i]->read_item (&(in_objects[i])))
	  != AMI_ERROR_NO_ERROR) {
	 if (ami_err != AMI_ERROR_END_OF_STREAM) {
	     delete[] in_objects;
	     return ami_err;
	 }
      }

      if (ami_err == AMI_ERROR_END_OF_STREAM) {
	 MergeHeap.delete_min_and_insert ((T *) NULL);
      } else {
	 MergeHeap.delete_min_and_insert (in_objects[i]);
      }
   }	//while

   return AMI_ERROR_NO_ERROR;
}

// **************************************************************************
// *                                                                        *
// *   A M I _ p a r t i t i o n _ a n d _ m e r g e _ d h                  *
// *                                                                        *
// **************************************************************************

template < class T, class M >
    AMI_err
AMI_partition_and_merge_dh (AMI_STREAM < T > *inStream,
			    AMI_STREAM < T > *outStream, M mgmt_obj)
{
   AMI_err         ae;
   TPIE_OS_OFFSET  len;
   size_t          sz_avail, szStream;
   size_t          szSubstream;

   unsigned int ii, jj;
   unsigned int iiStreams;

   char         *working_disk;

   LOG_DEBUG_ID ("AMI_partition_and_merge START");

   // Figure out how much memory we've got to work with.
   sz_avail = MM_manager.memory_available ();

   // Conservatively assume that the memory for buffers for
   // the two streams is unallocated; so we need to subtract.
   if ((ae = inStream->main_memory_usage
            (&szStream,MM_STREAM_USAGE_MAXIMUM)) != AMI_ERROR_NO_ERROR) {
      LOG_DEBUG_ID ("Error returned from main_memory_usage");
      return ae; // LOG_FATAL was reported in main_memory_usage
   }
   if ((ae = inStream->main_memory_usage
            (&szSubstream,MM_STREAM_USAGE_OVERHEAD)) != AMI_ERROR_NO_ERROR) {
      LOG_DEBUG_ID ("Error returned from main_memory_usage");
      return ae;
   }
   sz_avail -= 2 * szStream;

   working_disk = tpie_tempnam("AMI");

   // ***************************************************************
   // * If the input stream fits into main memory, special case     *
   // ***************************************************************

   len = inStream->stream_len ();
   inStream->seek (0);

   if (mgmt_obj.sort_fits_in_memory (inStream, sz_avail)){
      if ((ae= mgmt_obj.main_mem_operate_init (len) ) !=
	       AMI_ERROR_NO_ERROR) {
         LOG_FATAL_ID ("main_mem_operate_init failed");
         return ae;
      }
      if ((ae = mgmt_obj.main_mem_operate (inStream, outStream, len)) !=
	 AMI_ERROR_NO_ERROR) {
	 LOG_FATAL_ID ("main_mem_operate failed");
	 return ae;
      }
      mgmt_obj.main_mem_operate_cleanup ();

      return AMI_ERROR_NO_ERROR;
   };

   // ******************************************************************
   // * Input stream too large for main memory, use general merge sort *
   // ******************************************************************

   LOG_DEBUG_ID ("Beginning general merge sort.");

   // The number of substreams that the original input stream
   // will be split into.
   arity_t origSubstreams;

   // The length, in terms of stream objects of type T, of the
   // original substreams of the input stream.  The last one may
   // be shorter than this.
   size_t szOrigSubstream;

   // The initial temporary stream, to which substreams of the
   // original input stream are written.
   AMI_STREAM < T > **initialTmpStream;

   // The number of substreams that can be merged together at once.
   arity_t mrgArity;

   // The stream being read at the current level.
   AMI_STREAM < T > **currInput;

   // The output stream for the current level if it is not outStream.
   AMI_STREAM < T > **tmpStream;

   char *prefixName[] = { "_0_", "_1_" };

   // The size of substreams of *currInput that are being
   // merged.  The last one may be smaller.  This value should be
   // szOrigSubstream * (mrgArity ** mrgHgt) where mrgHgt is the
   // number of iterations the loop has gone through.
   unsigned int mrgHgt;

   TPIE_OS_OFFSET sub_start, sub_end;

   // How many substreams will there be?  The main memory
   // available to us is the total amount available, minus what
   // is needed for the input stream and the temporary stream.

   //RAKESH In our case mrgArity is determined differently than in the
   //orig implementation of AMI_partition_and_merge since we use
   //several streams in each level.  In our case net main memory
   //required to carry out an R-way merge is

   // (R+1)*MM_STREAM_USAGE_MAXIMUM  {R substr input runs, 1 stream output}
   // + R*MM_STREAM_USAGE_OVERHEAD   {1 stream each active input run: but
   //                                 substreams use buffers, streams don't}
   // + (R+1)*m_obj->space_usage_per_stream();
   //
   // The net memory usage for an R-way merge is thus
   // R*(szStream + sz_substream + space_usage_per_stream()) + szStream +
   // space_usage_per_stream();

   //To support a binary merge, need space for max_stream_usage
   //for at least three stream objects.

   if (sz_avail <= 3 *(szStream + szSubstream + sizeof(heap_element < T >))) {
      LOG_FATAL_ID ("Insufficient Memory for AMI_partition_and_merge");
      return AMI_ERROR_INSUFFICIENT_MAIN_MEMORY;
   }

   LOG_DEBUG_ID ("Each object of size " << sizeof(T) <<
       " has overhead of " << mgmt_obj.space_usage_overhead () << " bytes." );
   szOrigSubstream = (sz_avail) / (sizeof (T) + mgmt_obj.space_usage_overhead ());

   // ** modified 2001/04/23 dh : round DOWN instead of UP
   // otherwise we might attempt an external sort with only one
   // input stream to the merge.

   // Round the original substream length down to an integral number of
   // chunks.  This is for systems like HP-UX that cannot map in
   // overlapping regions.  It is also required for BTE's that are
   // capable of freeing chunks as they are read.

   size_t chunkSize = inStream->chunk_size ();
   // 2001/04/23 dh. was : szOrigSubstream = chunkSize *
   //                      ((szOrigSubstream + chunkSize-1) / chunkSize);
   szOrigSubstream = chunkSize * (szOrigSubstream / chunkSize);

   if (szOrigSubstream == 0) {
      LOG_FATAL_ID ("Insufficient Memory for AMI_partition_and_merge.");
      return AMI_ERROR_INSUFFICIENT_MAIN_MEMORY;
   }

   origSubstreams = (len + szOrigSubstream - 1) / szOrigSubstream;
   // We should always end up with at least two runs
   // otherwise why are we doing it externally?
   tp_assert (origSubstreams > 1, "Less than two runs to merge!");

   // Available memory for input stream objects is given by
   // sz_avail minus the space occupied by output stream objects.
   size_t sz_avail_during_merge = sz_avail - szStream - szSubstream;

   // This counts the per-input stream memory cost.
   size_t szPerInputStream = szStream + szSubstream + sizeof(heap_element<T>);

   // Compute merge arity
   mrgArity = sz_avail_during_merge / szPerInputStream;

   // Make sure that the AMI is willing to provide us with the
   // number of substreams we want.  It may not be able to due to
   // operating system restrictions, such as on the number of
   // regions that can be mmap()ed in.

   int availableStreams = inStream->available_streams ();

   if (availableStreams != -1) {
      if (availableStreams <= 5) {
	 LOG_FATAL_ID ("Not enough substreams available to perform merge.");
	 return AMI_ERROR_INSUFFICIENT_AVAILABLE_STREAMS;
      }

      if (mrgArity > (arity_t) availableStreams - 2) {
	 mrgArity = availableStreams - 2;
	 LOG_WARNING_ID ("Reduced merge arity due to AMI restrictions.");
      }
   }

   LOG_DEBUG_ID ("merge arity = " << mrgArity << ".");

   if (mrgArity < 2) {
      LOG_FATAL_ID ("Merge arity < 2! Insufficient memory for a merge.");
      return AMI_ERROR_INSUFFICIENT_MAIN_MEMORY;
   }

   //#define MINIMIZE_INITIAL_SUBSTREAM_LENGTH
#ifdef MINIMIZE_INITIAL_SUBSTREAM_LENGTH
   LOG_DEBUG_ID ("Minimizing initial run lengths without increasing" <<
		    "the height of the merge tree.");
   // Make the substreams as small as possible without increasing
   // the height of the merge tree.

   // The tree height is the ceiling of the log base mrgArity of the
   // number of original substreams.
   double tree_height = log((double)origSubstreams) / log((double)mrgArity);
   tp_assert (tree_height > 0, "Negative or zero tree height!");
   tree_height = ceil (tree_height);

   // See how many substreams we could possibly fit in the
   // tree without increasing the height.
   double maxOrigSubstreams = pow ((double) mrgArity, tree_height);
   tp_assert (maxOrigSubstreams >= origSubstreams,
		 "Number of permitted substreams was reduced.");

   // How big will such substreams be?
   double new_szOrigSubstream = ceil ((double) max lenOrigSubstreams);
   tp_assert (new_szOrigSubstream <= szOrigSubstream,
		 "Size of original streams increased.");

   szOrigSubstream = (size_t) new_szOrigSubstream;

   LOG_DEBUG_ID ("Memory constraints set original substreams = " <<
		    origSubstreams << '\n');

   origSubstreams = (len + szOrigSubstream - 1) / szOrigSubstream;

   LOG_DEBUG_ID ("Tree height constraints set original substreams = "
		    << origSubstreams << '\n');
#endif	// MINIMIZE_INITIAL_SUBSTREAM_LENGTH

   // Create a temporary stream, then iterate through the
   // substreams, processing each one and writing it to the
   // corresponding substream of the temporary stream.

   VarArray3D<unsigned int> runLens(2,mrgArity,(origSubstreams+mrgArity-1) / mrgArity);
   VarArray1D<int>          Sub_Start(mrgArity);

   // for (int i = 0; i < 2; i++)
   //    for (int j = 0; j < mrgArity; j++)
   //       for (int k1 = 0;
   //            k1 <  (origSubstreams+mrgArity-1)/mrgArity;
   //            k1++)
   //          runLens[i][j][k1] = 0;

   // Comment: (jan) Initialization is done in the VarArray3D constructor.

   // // memset ((void *) runLens, 0,
   // //   	   2 * mrgArity * ((origSubstreams + mrgArity - 1) /
   // //   			      mrgArity) * sizeof (unsigned int));

   // End Comment.

   LOG_DEBUG_ID("Allocating " << sizeof(AMI_STREAM<T>*)*mrgArity <<
                " bytes for " << mrgArity <<
                " initialTmpStream pointers. Mem. avail. is " <<
                MM_manager.memory_available () );
   initialTmpStream = new AMI_STREAM<T>* [mrgArity];

   if ((ae = mgmt_obj.main_mem_operate_init(szOrigSubstream)) !=
	    AMI_ERROR_NO_ERROR) {
      LOG_FATAL_ID ("main_mem_operate_init failed");
      return ae;
   }

   inStream->seek (0);

   tp_assert (origSubstreams * szOrigSubstream - len < szOrigSubstream,
	      "Total substream length too long or too many.");
   tp_assert (len - (origSubstreams - 1) * szOrigSubstream <= szOrigSubstream,
	      "Total substream length too short or too few.");

   TPIE_OS_OFFSET check_size            = 0;
   int    currStream            = mrgArity - 1;
   int    runsInCurrStream      = 0;
   char   newName [BTE_STREAM_PATH_NAME_LEN];

   VarArray1D<int>  reqdRuns(mrgArity);

   //For the first stream:
   for (iiStreams = 0; iiStreams < mrgArity; iiStreams++) {

      // Figure out how many runs go in each one of mrgArity
      // streams?  If there are 12 runs to be distributed among 5
      // streams, the first three get 2 and the last two get 3 runs

      if (iiStreams < (mrgArity - (origSubstreams % mrgArity)))
	 reqdRuns(iiStreams) = origSubstreams / mrgArity;
      else
	 reqdRuns(iiStreams) = (origSubstreams + mrgArity - 1) / mrgArity;
   }

#ifdef BTE_IMP_USER_DEFINED
   makeName ("", prefixName[0], currStream, newName);
#else
   //The assumption here is that working_disk is the name of the specific
   //directory in which the temporary/intermediate streams will be made.
   makeName (working_disk, prefixName[0], currStream, newName);
#endif

   LOG_DEBUG_ID("Allocating " << sizeof(AMI_STREAM<T>) <<
                " bytes for initialTmpStream[" << currStream <<
            "]. Mem. avail. is " << MM_manager.memory_available () );
   initialTmpStream[currStream] = new AMI_STREAM < T > (newName);
   initialTmpStream[currStream]->persist (PERSIST_PERSISTENT);

   ii = 0;
   while (ii < origSubstreams) {
      TPIE_OS_OFFSET mm_len;

      // ****************************************************************
      // * Make sure that the current stream is supposed to get a run   *
      // ****************************************************************

      if (reqdRuns(currStream) > runsInCurrStream) {
	 if (ii == origSubstreams - 1) {
	    mm_len = len % szOrigSubstream;

	    // If it is an exact multiple, then the mod will come out
	    // 0, which is wrong.
	    if (!mm_len) {
	       mm_len = szOrigSubstream;
	    }
	 } else {
	    mm_len = szOrigSubstream;
	 }

         if ((ae = mgmt_obj.main_mem_operate (inStream, initialTmpStream[currStream], mm_len)) !=
	    AMI_ERROR_NO_ERROR) {
	    LOG_FATAL_ID ("main_mem_operate failed");
	    return ae;
         }

         runLens(0,currStream,runsInCurrStream) = mm_len;
	 runsInCurrStream++;
	 ii++;
      } // end  if (reqdRuns(currStream) > runsInCurrStream)

      if (runsInCurrStream == reqdRuns(currStream)) {

	 check_size += initialTmpStream[currStream]->stream_len ();

	 // We do not want old streams hanging around
	 // occuping memory. We know how to get the streams
	 // since we can generate their names

	 if (initialTmpStream[currStream]) {
	    delete initialTmpStream[currStream];
	    initialTmpStream[currStream] = NULL;
	 }

	 if (check_size < inStream->stream_len ()) {
	    currStream = (currStream + mrgArity - 1) % mrgArity;
#ifdef BTE_IMP_USER_DEFINED
	    makeName ("", prefixName[0], currStream, newName);
#else
	    makeName (working_disk, prefixName[0], currStream, newName);
#endif
            LOG_DEBUG_ID("Allocating " << sizeof(AMI_STREAM<T>) <<
              " bytes  for initialTmpStream[" << currStream <<
              "]. Mem. avail. is " << MM_manager.memory_available () );
	    initialTmpStream[currStream] = new AMI_STREAM < T > (newName);
	    initialTmpStream[currStream]->persist (PERSIST_PERSISTENT);
	    runsInCurrStream = 0;
	 }
      } // end if (runsInCurrStream == reqdRuns(currStream))
   } // end while (ii < origSubstreams)

   if (initialTmpStream[currStream]) {
      delete initialTmpStream[currStream];
      initialTmpStream[currStream] = NULL;
   }

   mgmt_obj.main_mem_operate_cleanup ();

   // Make sure the total length of the temporary stream is the
   // same as the total length of the original input stream.
   tp_assert (inStream->stream_len () == check_size,
	      "Stream lengths do not match:" <<
	      "\n\tinStream->stream_len() = " << inStream->stream_len ()
	      << "\n\tinitialTmpStream->stream_len() = " << check_size
	      << ".");

   LOG_DEBUG_ID ("Initial number of runs " << origSubstreams );
   LOG_DEBUG_ID ("Merge arity is " << mrgArity );

   // Pointers to the substreams that will be merged.

   LOG_DEBUG_ID("Allocating " << sizeof(AMI_STREAM<T>*)*mrgArity <<
                " bytes for " << mrgArity <<
                " theSubstreams pointers. Mem. avail. is " <<
                MM_manager.memory_available () );
   AMI_STREAM <T> **theSubstreams = new AMI_STREAM<T>* [mrgArity];

   mrgHgt = 0;
   currInput = initialTmpStream;
   // Allocate room for the merge heap
   mgmt_obj.MergeHeap.allocate( mrgArity );

   // ***********************************************************************
   // *                                                                     *
   // * The main loop.  At the outermost level we are looping over          *
   // * levels of the merge tree.  Typically this will be very small,       *
   // * e.g. 1-3.                                                           *
   // *                                                                     *
   // ***********************************************************************

   // The number of substreams to be processed at any merge level.
   arity_t ssCount;

   for (ssCount = origSubstreams; ssCount > 1;
        ssCount = (ssCount + mrgArity - 1) / mrgArity) {

      // Set up to process a given level.

      tp_assert (len == check_size,
		 "Current level stream not same length as input." <<
		 "\n\tlen = " << len <<
		 "\n\tcurrInput->stream_len() = " <<
		 check_size << ".");

      // [tavi, 01/05/02] Commented this assignment out, since it
      // causes the above assert to fail when input size is much
      // higher than the memory (because the number of iterations of
      // this for loop executed is at least 2). check_size doesn't
      // seem to be used anywhere else in this loop.

      //  check_size = 0;

      // Do we have enough main memory to merge all the
      // substreams on the current level into the output stream?
      // If so, then we will do so, if not then we need an
      // additional level of iteration to process the substreams
      // in groups.

      if (ssCount <= mrgArity) {

         // Open up the ssCount streams in which the
         // the runs input to the current merge level are packed
         // The names of these streams (storing the input runs)
         // can be constructed from  prefixName[mrgHgt % 2]

	 for (ii = mrgArity - ssCount; ii < mrgArity; ii++) {

#ifdef  BTE_IMP_USER_DEFINED
	    makeName ("", prefixName[mrgHgt % 2], (int) ii, newName);
#else
	    makeName (working_disk, prefixName[mrgHgt % 2], (int) ii, newName);
#endif
            LOG_DEBUG_ID("Allocating " << sizeof(AMI_STREAM<T>) <<
              " bytes  for currInput[" << ii <<
              "]. Mem. avail. is " << MM_manager.memory_available () );
	    currInput[ii] = new AMI_STREAM < T > (newName);
	    currInput[ii]->persist (PERSIST_DELETE);
	 }

	 // Merge them into the output stream.
	 // currInput is address( address (the first input stream) )

         ae = mgmt_obj.single_merge (currInput + mrgArity - ssCount,
                                    ssCount, outStream );

	 if (ae != AMI_ERROR_NO_ERROR) {
            LOG_FATAL_ID ("AMI_ERROR " << ae << " returned by single_merge");
	    return ae;
	 }

	 // Delete the streams input to the above merge.
	 for (ii = mrgArity - ssCount; ii < mrgArity; ii++) {
	    if (currInput[ii]) {
	       delete currInput[ii];
	       currInput[ii] = NULL;
	    }
	 }
	 if (currInput) {
	    delete[]currInput;
	    currInput = initialTmpStream = NULL;
	 }
	 if (theSubstreams) {
	    delete[]theSubstreams;
	    theSubstreams = NULL;
	 }

      } else { // (ssCount > mrgArity)

	 LOG_DEBUG_ID ("Merging substreams to intermediate streams.");

	 // Create the array of mrgArity stream pointers that
	 // will each point to a stream containing runs output
	 // at the current level mrgHgt.

         LOG_DEBUG_ID("Allocating " << sizeof(AMI_STREAM<T>*)*mrgArity <<
                " bytes for " << mrgArity <<
                " tmpStream pointers. Mem. avail. is " <<
                MM_manager.memory_available () );
	 tmpStream = new AMI_STREAM<T>* [mrgArity];

         // Open up the mrgArity streams in which the
         // the runs input to the current merge level are packed
         // The names of these streams (storing the input runs)
         // can be constructed from  prefixName[mrgHgt % 2]

	 for (ii = 0; ii < mrgArity; ii++) {
#ifdef BTE_IMP_USER_DEFINED
	    makeName ("", prefixName[mrgHgt % 2], (int) ii, newName);
#else
	    makeName (working_disk, prefixName[mrgHgt % 2], (int) ii, newName);
#endif
            LOG_DEBUG_ID("Allocating " << sizeof(AMI_STREAM<T>) <<
              " bytes  for currInput[" << ii <<
              "]. Mem. avail. is " << MM_manager.memory_available () );
	    currInput[ii] = new AMI_STREAM < T > (newName);
	    currInput[ii]->persist (PERSIST_DELETE);
	 }

	 // Fool the OS into unmapping the current block of the
	 // input stream so that blocks of the substreams can
	 // be mapped in without overlapping it.  This is
	 // needed for correct execution on HP-UX.
         //RAKESH
         //                currInput->seek(0);

	 currStream = mrgArity - 1;

	 //For the first stream that we use to pack some
	 //of the output runs of the current merge level mrgHgt.

#ifdef BTE_IMP_USER_DEFINED
	 makeName("", prefixName[(mrgHgt + 1) % 2], currStream, newName);
#else
	 makeName(working_disk, prefixName[(mrgHgt + 1) % 2], currStream, newName);
#endif

         LOG_DEBUG_ID("Allocating " << sizeof(AMI_STREAM<T>) <<
              " bytes  for tmpStream[" << currStream <<
              "]. Mem. avail. is " << MM_manager.memory_available () );
	 tmpStream[currStream] = new AMI_STREAM< T >(newName);
	 tmpStream[currStream]->persist (PERSIST_PERSISTENT);

	 int outRunsLeft = (ssCount + mrgArity - 1) / mrgArity;

	 for (iiStreams = 0; iiStreams < mrgArity; iiStreams++) {

	    // If there are 12 runs to be distributed among 5 streams,
	    // the first three get 2 and the last two  get 3 runs

	    if (iiStreams < (mrgArity - (outRunsLeft % mrgArity)))
	       reqdRuns(iiStreams) = outRunsLeft / mrgArity;
	    else
	       reqdRuns(iiStreams) = (outRunsLeft + mrgArity-1) / mrgArity;

	    Sub_Start(iiStreams) = 0;
	 }

	 unsigned int mergeNo = 0;
	 runsInCurrStream = 0;

         // **************************************************************
	 // * Loop through the substreams of the current stream, merging *
	 // * as many as we can at a time until all are done with.       *
         // **************************************************************

         //  [mrgHgt % 2]   lets us alternate between indices 0 and 1.
         //  jj        is number of substreams to be added so far to
         //            the merge.
         //  ssx       is the index of the substream currently being
         //            considered. ssx = mrgArity - 1 - jj

	 for (ii = 0, sub_start = 0, jj = 0; ii < ssCount; ii++) {

            int ssx = mrgArity - 1 - jj;
	    if (runLens(mrgHgt % 2,ssx,mergeNo)!= 0) {
	       sub_start       = Sub_Start(ssx);
	       sub_end         = sub_start + runLens(mrgHgt%2,ssx,mergeNo) - 1;
	       Sub_Start(ssx) += runLens(mrgHgt % 2,ssx,mergeNo);
	       runLens(mrgHgt % 2,ssx,mergeNo) = 0;
	    } else {
	       sub_end   = Sub_Start(ssx) - 1;
	       sub_start = sub_end + 1;
	       ii--;
	    }

	    //Open the new substream
	    currInput[ssx]-> new_substream
                     ( AMI_READ_STREAM, sub_start, sub_end,
		       (AMI_stream_base < T > **) (theSubstreams + jj) );

            // ***********************************************************
	    // * The substreams are read-once.  If we've got all we can  *
	    // * handle or we've seen them all, then merge them.         *
            // ***********************************************************

	    if ( (jj >= mrgArity - 1)||(ii == ssCount - 1) ) {

	       tp_assert( jj<=mrgArity-1, "Index got too large." );

	       //Check if the stream into which runs are cuurently
	       //being packed has got its share of runs. If yes,
	       //'delete' that stream and construct a new stream

	       if (reqdRuns(currStream) == runsInCurrStream) {

		  //Make sure that the deleted stream persists on disk.
		  tmpStream[currStream]->persist (PERSIST_PERSISTENT);
		  delete tmpStream[currStream];

		  currStream = (currStream + mrgArity - 1) % mrgArity;

		  // Unless the current level is over, we've to
		  // generate a new stream for the next set of runs.

		  if (outRunsLeft > 0) {
#ifdef BTE_IMP_USER_DEFINED
		     makeName ("", prefixName[(mrgHgt + 1) % 2],
				       (int) currStream, newName);
#else
		     makeName (working_disk, prefixName[(mrgHgt + 1) % 2],
				       (int) currStream, newName);
#endif
                     LOG_DEBUG_ID("Allocating " << sizeof(AMI_STREAM<T>) <<
                                 " bytes  for tmpStream[" << currStream <<
                                 "]. Mem. avail. is " <<
                                 MM_manager.memory_available () );
		     tmpStream[currStream] = new AMI_STREAM < T > (newName);
		     tmpStream[currStream]->persist(PERSIST_PERSISTENT);
		     runsInCurrStream = 0;
		  }
	       }

	       ae = mgmt_obj.single_merge ( theSubstreams, jj + 1,
		     tmpStream [currStream] );
	       if (ae != AMI_ERROR_NO_ERROR) {
                   LOG_FATAL_ID ("AMI_single_merge error" << ae);
		  return ae;
	       }

	       for (iiStreams = 0; iiStreams < jj + 1; iiStreams++)
		   runLens((mrgHgt + 1) % 2,currStream,runsInCurrStream)
                      += theSubstreams[iiStreams]->stream_len ();

	       mergeNo++;

	       //Decrement the number of runs still to be formed at
	       //current level

	       outRunsLeft--;

	       // Delete input substreams. jj is the index of the last one.

	       for (iiStreams = 0; iiStreams < jj + 1; iiStreams++) {
		  if (theSubstreams[iiStreams]) {
		     delete theSubstreams[iiStreams];
		     theSubstreams[iiStreams] = NULL;
		  }
	       }

	       jj = 0;
	       runsInCurrStream++;
	    } else { // Keep adding substreams
	       jj++;
	    }
	 }

	 if (tmpStream[currStream]) {
	    delete tmpStream[currStream];
	    tmpStream[currStream] = NULL;
	 }

	 // Get rid of the current input streams and use the ones
	 // output at the current level.

	 for (ii = 0; ii < mrgArity; ii++)
	    if (currInput[ii]) {
	       delete currInput[ii];
	    }
	 if (currInput) {
	    delete[]currInput;
	    currInput = NULL;
	 }
	 currInput = (AMI_STREAM < T > **)  tmpStream;
      }
      mrgHgt++;
   }
   // Deallocate the merge heap
   mgmt_obj.MergeHeap.deallocate( );

   //Monitoring prints.
   LOG_DEBUG_ID ("Number of passes incl run formation is " << mrgHgt+1 );
   LOG_DEBUG_ID ("AMI_partition_and_merge END");
   return AMI_ERROR_NO_ERROR;
}
#endif //_APM_DH_H


text:
package fake

import (
	policy "k8s.io/api/policy/v1beta1"
	"k8s.io/apimachinery/pkg/runtime/schema"
	core "k8s.io/client-go/testing"
)

func (c *FakeEvictions) Evict(eviction *policy.Eviction) error {
	action := core.GetActionImpl{}
	action.Verb = "post"
	action.Namespace = c.ns
	action.Resource = schema.GroupVersionResource{Group: "", Version: "", Resource: "pods"}
	action.Subresource = "eviction"
	_, err := c.Fake.Invokes(action, eviction)
	return err
}


text:
import * as React from 'react';
import { Sizes } from 'react-bootstrap';

declare namespace Label {
    export interface LabelProps extends React.HTMLProps<Label> {
        bsSize?: Sizes | undefined;
        bsStyle?: string | undefined;
    }
}
declare class Label extends React.Component<Label.LabelProps> { }
export = Label;


text:
package com.facebook.buck.android;

import static com.facebook.buck.model.HasBuildTarget.TO_TARGET;

import com.facebook.buck.android.AndroidBinary.ExopackageMode;
import com.facebook.buck.android.AndroidBinary.PackageType;
import com.facebook.buck.android.ResourcesFilter.ResourceCompressionMode;
import com.facebook.buck.jvm.java.Classpaths;
import com.facebook.buck.jvm.java.JavaLibrary;
import com.facebook.buck.jvm.java.JavacOptions;
import com.facebook.buck.model.BuildTarget;
import com.facebook.buck.model.HasBuildTarget;
import com.facebook.buck.parser.NoSuchBuildTargetException;
import com.facebook.buck.rules.AbstractDescriptionArg;
import com.facebook.buck.rules.BuildRule;
import com.facebook.buck.rules.BuildRuleParams;
import com.facebook.buck.rules.BuildRuleResolver;
import com.facebook.buck.rules.BuildRuleType;
import com.facebook.buck.rules.Description;
import com.facebook.buck.rules.InstallableApk;
import com.facebook.buck.rules.SourcePath;
import com.facebook.buck.rules.SourcePathResolver;
import com.facebook.buck.rules.TargetGraph;
import com.facebook.buck.rules.coercer.BuildConfigFields;
import com.facebook.buck.util.HumanReadableException;
import com.facebook.infer.annotation.SuppressFieldNotInitialized;
import com.google.common.base.Optional;
import com.google.common.base.Suppliers;
import com.google.common.collect.FluentIterable;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.ImmutableSortedSet;
import com.google.common.collect.Iterables;
import com.google.common.util.concurrent.ListeningExecutorService;

import java.nio.file.Path;
import java.util.EnumSet;

public class AndroidInstrumentationApkDescription
    implements Description<AndroidInstrumentationApkDescription.Arg> {

  public static final BuildRuleType TYPE = BuildRuleType.of("android_instrumentation_apk");

  private final ProGuardConfig proGuardConfig;
  private final JavacOptions javacOptions;
  private final ImmutableMap<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform> nativePlatforms;
  private final ListeningExecutorService dxExecutorService;

  public AndroidInstrumentationApkDescription(
      ProGuardConfig proGuardConfig,
      JavacOptions androidJavacOptions,
      ImmutableMap<NdkCxxPlatforms.TargetCpuType, NdkCxxPlatform> nativePlatforms,
      ListeningExecutorService dxExecutorService) {
    this.proGuardConfig = proGuardConfig;
    this.javacOptions = androidJavacOptions;
    this.nativePlatforms = nativePlatforms;
    this.dxExecutorService = dxExecutorService;
  }

  @Override
  public BuildRuleType getBuildRuleType() {
    return TYPE;
  }

  @Override
  public Arg createUnpopulatedConstructorArg() {
    return new Arg();
  }

  @Override
  public <A extends Arg> BuildRule createBuildRule(
      TargetGraph targetGraph,
      BuildRuleParams params,
      BuildRuleResolver resolver,
      A args) throws NoSuchBuildTargetException {
    BuildRule installableApk = resolver.getRule(args.apk);
    if (!(installableApk instanceof InstallableApk)) {
      throw new HumanReadableException(
          "In %s, apk='%s' must be an android_binary() or apk_genrule() but was %s().",
          params.getBuildTarget(),
          installableApk.getFullyQualifiedName(),
          installableApk.getType());
    }
    AndroidBinary apkUnderTest = getUnderlyingApk((InstallableApk) installableApk);

    ImmutableSortedSet<JavaLibrary> rulesToExcludeFromDex = FluentIterable.from(
        ImmutableSet.<JavaLibrary>builder()
            .addAll(apkUnderTest.getRulesToExcludeFromDex())
            .addAll(Classpaths.getClasspathEntries(apkUnderTest.getClasspathDeps()).keySet())
            .build())
        .toSortedSet(HasBuildTarget.BUILD_TARGET_COMPARATOR);

    // TODO(natthu): Instrumentation APKs should also exclude native libraries and assets from the
    // apk under test.
    AndroidPackageableCollection.ResourceDetails resourceDetails =
        apkUnderTest.getAndroidPackageableCollection().getResourceDetails();
    ImmutableSet<BuildTarget> resourcesToExclude = ImmutableSet.copyOf(
        Iterables.concat(
            resourceDetails.getResourcesWithNonEmptyResDir(),
            resourceDetails.getResourcesWithEmptyResButNonEmptyAssetsDir()));

    Path primaryDexPath = AndroidBinary.getPrimaryDexPath(params.getBuildTarget());
    AndroidBinaryGraphEnhancer graphEnhancer = new AndroidBinaryGraphEnhancer(
        params,
        resolver,
        ResourceCompressionMode.DISABLED,
        FilterResourcesStep.ResourceFilter.EMPTY_FILTER,
        /* resourceUnionPackage */ Optional.<String>absent(),
        /* locales */ ImmutableSet.<String>of(),
        args.manifest,
        PackageType.INSTRUMENTED,
        apkUnderTest.getCpuFilters(),
        /* shouldBuildStringSourceMap */ false,
        /* shouldPreDex */ false,
        primaryDexPath,
        DexSplitMode.NO_SPLIT,
        FluentIterable.from(rulesToExcludeFromDex).transform(TO_TARGET).toSet(),
        resourcesToExclude,
        /* skipCrunchPngs */ false,
        javacOptions,
        EnumSet.noneOf(ExopackageMode.class),
        apkUnderTest.getKeystore(),
        /* buildConfigValues */ BuildConfigFields.empty(),
        /* buildConfigValuesFile */ Optional.<SourcePath>absent(),
        /* xzCompressionLevel */ Optional.<Integer>absent(),
        nativePlatforms,
        AndroidBinary.RelinkerMode.DISABLED,
        dxExecutorService);

    AndroidGraphEnhancementResult enhancementResult =
        graphEnhancer.createAdditionalBuildables();

    return new AndroidInstrumentationApk(
        params
            .copyWithExtraDeps(Suppliers.ofInstance(enhancementResult.getFinalDeps()))
            .appendExtraDeps(rulesToExcludeFromDex),
        new SourcePathResolver(resolver),
        proGuardConfig.getProguardJarOverride(),
        proGuardConfig.getProguardMaxHeapSize(),
        proGuardConfig.getProguardAgentPath(),
        apkUnderTest,
        rulesToExcludeFromDex,
        enhancementResult,
        dxExecutorService);

  }

  private static AndroidBinary getUnderlyingApk(InstallableApk installable) {
    if (installable instanceof AndroidBinary) {
      return (AndroidBinary) installable;
    } else if (installable instanceof ApkGenrule) {
      return getUnderlyingApk(((ApkGenrule) installable).getInstallableApk());
    } else {
      throw new IllegalStateException(
          installable.getBuildTarget().getFullyQualifiedName() +
              " must be backed by either an android_binary() or an apk_genrule()");
    }
  }

  @SuppressFieldNotInitialized
  public static class Arg extends AbstractDescriptionArg {
    public SourcePath manifest;
    public BuildTarget apk;
    public Optional<ImmutableSortedSet<BuildTarget>> deps;
  }
}


text:
// CppNumericalSolver
#ifndef WOLFERULE_H_
#define WOLFERULE_H_

#include "../meta.h"

namespace cppoptlib {

/**
 * @brief this tries to guess the correct stepwith in a bisection-style
 * @details WARNING: THIS IS QUITE HACKY. TEST ARMIJO before.
 *
 * @tparam T scalar type
 * @tparam P problem type
 * @tparam Ord order of solver
 */
template<typename T, typename P, int Ord>
class WolfeHeuristic {

 public:

  static T linesearch(const Vector<T> & x0, const Vector<T> & searchDir, P &objFunc, const T alpha_init = 1) {

    Vector<T> x = x0;

    // evaluate phi(0)
    T phi0 = objFunc.value(x0);
    // evaluate phi'(0)
    Vector<T> grad(x.rows());
    objFunc.gradient(x, grad);

    T phi0_dash = searchDir.dot(grad);

    T alpha = alpha_init;
    bool decrease_direction = true;

    // 200 guesses
    for(size_t iter = 0; iter < 200; ++iter) {

      // new guess for phi(alpha)
      Vector<T> x_candidate = x + alpha * searchDir;
      const T phi = objFunc.value(x_candidate);

      // decrease condition invalid --> shrink interval
      if (phi > phi0 + 0.0001 * alpha * phi0_dash) {
        alpha *= 0.5;
        decrease_direction = false;
      } else {

        // valid decrease --> test strong wolfe condition
        Vector<T> grad2(x.rows());
        objFunc.gradient(x_candidate, grad2);
        const T phi_dash = searchDir.dot(grad2);

        // curvature condition invalid ?
        if ((phi_dash < 0.9 * phi0_dash) || !decrease_direction) {
          // increase interval
          alpha *= 4.0;
        } else {
          // both condition are valid --> we are happy
          x = x_candidate;
          grad = grad2;
          phi0 = phi;
          return alpha;
        }
      }
    }

    return alpha;
  }

};
}

#endif /* WOLFERULE_H_ */


text:
<?xml version="1.0" encoding="UTF-8"?>
<!-- $Id: dcm4chee-exportmanager-service.xml 11329 2009-05-12 15:02:23Z gunterze $ -->
<server>
  <classpath codebase="lib" archives="dcm4chee.jar"/>
  <mbean code="org.jboss.mq.server.jmx.Queue"
    name="dcm4chee.archive:service=Queue,name=ExportManager">
    <depends optional-attribute-name="DestinationManager"
      >jboss.mq:service=DestinationManager</depends>
  </mbean>
  <mbean code="org.dcm4chex.archive.tce.ExportManagerService"
    name="dcm4chee.archive:service=ExportManager"
    xmbean-dd="xmdesc/dcm4chee-exportmanager-xmbean.xml">
    <depends optional-attribute-name="AuditLoggerName"
      >dcm4chee.archive:service=AuditLogger</depends>
    <depends optional-attribute-name="QueryRetrieveScpServiceName"
      >dcm4chee.archive:service=QueryRetrieveScp</depends>
    <depends optional-attribute-name="IANScuServiceName"
      >dcm4chee.archive:service=IANScu</depends>
    <depends optional-attribute-name="JMSServiceName"
      >dcm4chee.archive:service=JMS</depends>
    <depends optional-attribute-name="StoreScpServiceName"
      >dcm4chee.archive:service=StoreScp</depends>
    <depends optional-attribute-name="TemplatesServiceName"
      >dcm4chee.archive:service=Templates</depends>
    <depends optional-attribute-name="TLSConfigName"
      >dcm4chee.archive:service=TLSConfig</depends>
    <depends>dcm4chee.archive:service=Queue,name=ExportManager</depends>
    <attribute name="QueueName">ExportManager</attribute>
  </mbean>
</server>


text:
from __future__ import annotations

from flask import Blueprint, redirect, url_for

routes = Blueprint('routes', __name__)

@routes.route('/')
def index():
    """Main Airflow page"""
    return redirect(url_for('Airflow.index'))


text:
<?xml version="1.0" encoding="UTF-8" ?>
<beans xmlns="http://www.springframework.org/schema/beans"
	   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
	   xmlns:tx="http://www.springframework.org/schema/tx"
	   xmlns:context="http://www.springframework.org/schema/context"
	   xmlns:util="http://www.springframework.org/schema/util"
	   xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
	   					   http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/spring-tx.xsd
	   					   http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
                           http://www.springframework.org/schema/util http://www.springframework.org/schema/util/spring-util.xsd">

	<tx:annotation-driven/>
	<context:spring-configured/>
	<context:annotation-config/>
	<context:component-scan base-package="net.airlinetycoon"/>

	<bean id="airlinetycoonDS" class="org.springframework.jdbc.datasource.DriverManagerDataSource">
		<property name="driverClassName" value="org.postgresql.Driver" />
		<property name="url" value="jdbc:postgresql://127.0.0.1:5432/airlinetycoon" />
		<property name="username" value="airlinetycoon" />
		<property name="password" value="airlinetycoon" />
	</bean>

	<bean id="jpaVendorAdapter" class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter">
		<property name="showSql" value="true"/>
	</bean>

	<bean id="transactionManager" class="org.springframework.orm.jpa.JpaTransactionManager">
		<property name="entityManagerFactory" ref="entityManagerFactory"/>
	</bean>

	<bean name="entityManagerFactory" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
		<property name="dataSource" ref="airlinetycoonDS"/>
		<property name="packagesToScan">
			<array>
				<value>net.airlinetycoon</value>
			</array>
		</property>
		<property name="jpaPropertyMap" ref="jpaPropertyMap"/>
		<property name="jpaVendorAdapter" ref="jpaVendorAdapter"/>
	</bean>

	<util:map id="jpaPropertyMap">
		<entry key="hibernate.hbm2ddl.auto" value="create"/>
		<entry key="hibernate.show_sql" value="true"/>
		<entry key="hibernate.dialect" value="org.hibernate.dialect.PostgreSQL9Dialect"/>
	</util:map>

</beans>


text:
package controlador;

import java.io.*;
import java.util.HashMap;
import java.util.Scanner;
import modelo.Materia;
import spark.*;

public class MostrarConteudo implements TemplateViewRoute {
	public ModelAndView handle(Request req, Response res) {
		Materia c = new Materia();
		HashMap dados = new HashMap();
		try {
		File dir = new File("Materias/Física 2");
		File[] arqs = dir.listFiles();
		for(File arq : arqs){ //For each
		Scanner scan = new Scanner(arq);
		String linha = scan.nextLine();
		String[] colunas = linha.split(";");
		c.setTitulo(colunas[0]);
		c.setConteudo(colunas[1]);
		scan.close();
		dados.put("conteudo", c);
		}
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return new ModelAndView(dados, "conteudo_teste.html");
	}
}


text:
package gov.nist.javax.sip.parser;

public class Lexer
  extends gov.nist.core.LexerCore{
  // Constructors

  public Lexer(java.lang.String arg1, java.lang.String arg2){
    super();
  }
  // Methods

  public static java.lang.String getHeaderName(java.lang.String arg1){
    return (java.lang.String) null;
  }
  public static java.lang.String getHeaderValue(java.lang.String arg1){
    return (java.lang.String) null;
  }
  public void selectLexer(java.lang.String arg1){
  }
}


text:
FROM node:dubnium-alpine

WORKDIR /usr/src/app

# install dependencies
COPY package.json .
RUN npm install

# install the app
COPY . .

EXPOSE 3000
CMD [ "npm", "start" ]


text:
package rappsilber.ms.dataAccess.filter.fastafilter;

import java.util.Collection;
import rappsilber.ms.sequence.Sequence;

/**
 *
 * @author Lutz Fischer <l.fischer@ed.ac.uk>
 */
public class NoFilter implements FastaFilter{

    public Sequence[] getSequences(Sequence s) {
        return new Sequence[]{s};
    }

    public Collection<Sequence> getSequences(Collection<Sequence> s) {
        return s;
    }

}


text:
@include('wargame::global-header')
@include('wargame::TMCW.Chawinda1965.chawinda1965Header')
<link rel="stylesheet" type="text/css" href="{{mix('vendor/css/wargame/chawinda1965.css')}}">

@section('zoc-rules')
    @include('wargame::TMCW.Chawinda1965.commonZocRules')
@endsection
@section('innerNextPhaseWrapper')
    <button class="dynamicButton movementButton" id="splitEvent">s</button>
    <button class="dynamicButton movementButton" id="combineEvent">c</button>
    @parent
@endsection
@section('unitRules')
    @parent

No units may be receive replacements in this game.

@endsection
@section('exclusiveRules')
    @include('wargame::TMCW.Chawinda1965.exclusiveRules')
@endsection
@section('victoryConditions')
    @include('wargame::TMCW.Chawinda1965.victoryConditions')
@endsection
@section('obc')
    @include('wargame::TMCW.Chawinda1965.obc')

X

Combined Units

@endsection
@section('commonStacking')
    @include('wargame::TMCW.Chawinda1965.commonStacking')
@endsection
@section('inner-crt')
    @include('wargame::stdIncludes.inner-crt', ['topCrt'=> $top_crt = new \Wargame\TMCW\Chawinda1965\CombatResultsTable()])
@endsection

@section('commonRules')
    @include('wargame::TMCW.commonRules')
@endsection

@section('exclusiveRules')
    @include('wargame::TMCW.exclusiveRules')
@endsection
@section('obc')
    @include('wargame::TMCW.obc')
@endsection
@extends('wargame::stdIncludes.view' )


text:
#ifndef BOOST_ASIO_BASIC_STREAMBUF_HPP
#define BOOST_ASIO_BASIC_STREAMBUF_HPP

#if defined(_MSC_VER) && (_MSC_VER >= 1200)
# pragma once
#endif // defined(_MSC_VER) && (_MSC_VER >= 1200)

#include <boost/asio/detail/push_options.hpp>

#include <boost/asio/detail/push_options.hpp>
#include <algorithm>
#include <limits>
#include <memory>
#include <stdexcept>
#include <streambuf>
#include <vector>
#include <boost/asio/detail/pop_options.hpp>

#include <boost/asio/buffer.hpp>
#include <boost/asio/detail/noncopyable.hpp>

namespace boost {
namespace asio {

/// Automatically resizable buffer class based on std::streambuf.
template <typename Allocator = std::allocator<char> >
class basic_streambuf
  : public std::streambuf,
    private noncopyable
{
public:
#if defined(GENERATING_DOCUMENTATION)
  /// The type used to represent the get area as a list of buffers.
  typedef implementation_defined const_buffers_type;

  /// The type used to represent the put area as a list of buffers.
  typedef implementation_defined mutable_buffers_type;
#else
  typedef boost::asio::const_buffers_1 const_buffers_type;
  typedef boost::asio::mutable_buffers_1 mutable_buffers_type;
#endif

  /// Construct a buffer with a specified maximum size.
  explicit basic_streambuf(
      std::size_t max_size = (std::numeric_limits<std::size_t>::max)(),
      const Allocator& allocator = Allocator())
    : max_size_(max_size),
      buffer_(allocator)
  {
    std::size_t pend = (std::min<std::size_t>)(max_size_, buffer_delta);
    buffer_.resize((std::max<std::size_t>)(pend, 1));
    setg(&buffer_[0], &buffer_[0], &buffer_[0]);
    setp(&buffer_[0], &buffer_[0] + pend);
  }

  /// Return the size of the get area in characters.
  std::size_t size() const
  {
    return pptr() - gptr();
  }

  /// Return the maximum size of the buffer.
  std::size_t max_size() const
  {
    return max_size_;
  }

  /// Get a list of buffers that represents the get area.
  const_buffers_type data() const
  {
    return boost::asio::buffer(boost::asio::const_buffer(gptr(),
          (pptr() - gptr()) * sizeof(char_type)));
  }

  /// Get a list of buffers that represents the put area, with the given size.
  mutable_buffers_type prepare(std::size_t size)
  {
    reserve(size);
    return boost::asio::buffer(boost::asio::mutable_buffer(
          pptr(), size * sizeof(char_type)));
  }

  /// Move the start of the put area by the specified number of characters.
  void commit(std::size_t n)
  {
    if (pptr() + n > epptr())
      n = epptr() - pptr();
    pbump(static_cast<int>(n));
  }

  /// Move the start of the get area by the specified number of characters.
  void consume(std::size_t n)
  {
    while (n > 0)
    {
      sbumpc();
      --n;
    }
  }

protected:
  enum { buffer_delta = 128 };

  int_type underflow()
  {
    if (gptr() < pptr())
    {
      setg(&buffer_[0], gptr(), pptr());
      return traits_type::to_int_type(*gptr());
    }
    else
    {
      return traits_type::eof();
    }
  }

  int_type overflow(int_type c)
  {
    if (!traits_type::eq_int_type(c, traits_type::eof()))
    {
      if (pptr() == epptr())
      {
        std::size_t buffer_size = pptr() - gptr();
        if (buffer_size < max_size_ && max_size_ - buffer_size < buffer_delta)
        {
          reserve(max_size_ - buffer_size);
        }
        else
        {
          reserve(buffer_delta);
        }
      }

      *pptr() = traits_type::to_char_type(c);
      pbump(1);
      return c;
    }

    return traits_type::not_eof(c);
  }

  void reserve(std::size_t n)
  {
    // Get current stream positions as offsets.
    std::size_t gnext = gptr() - &buffer_[0];
    std::size_t gend = egptr() - &buffer_[0];
    std::size_t pnext = pptr() - &buffer_[0];
    std::size_t pend = epptr() - &buffer_[0];

    // Check if there is already enough space in the put area.
    if (n <= pend - pnext)
    {
      return;
    }

    // Shift existing contents of get area to start of buffer.
    if (gnext > 0)
    {
      std::rotate(&buffer_[0], &buffer_[0] + gnext, &buffer_[0] + pend);
      gend -= gnext;
      pnext -= gnext;
    }

    // Ensure buffer is large enough to hold at least the specified size.
    if (n > pend - pnext)
    {
      if (n <= max_size_ && pnext <= max_size_ - n)
      {
        buffer_.resize((std::max<std::size_t>)(pnext + n, 1));
      }
      else
      {
        throw std::length_error("boost::asio::streambuf too long");
      }
    }

    // Update stream positions.
    setg(&buffer_[0], &buffer_[0], &buffer_[0] + gend);
    setp(&buffer_[0] + pnext, &buffer_[0] + pnext + n);
  }

private:
  std::size_t max_size_;
  std::vector<char_type, Allocator> buffer_;
};

} // namespace asio
} // namespace boost

#include <boost/asio/detail/pop_options.hpp>

#endif // BOOST_ASIO_BASIC_STREAMBUF_HPP