text:
'use strict';

/**
 * Represents a window in a possible chain of iframes
 */
export interface IWindowChainElement {
	/**
	 * The window object for it
	 */
	window: Window;
	/**
	 * The iframe element inside the window.parent corresponding to window
	 */
	iframeElement: HTMLIFrameElement;
}

var hasDifferentOriginAncestorFlag:boolean = false;
var sameOriginWindowChainCache:IWindowChainElement[] = null;

function getParentWindowIfSameOrigin(w:Window): Window {
	if (!w.parent || w.parent === w) {
		return null;
	}

	// Cannot really tell if we have access to the parent window unless we try to access something in it
	try {
		var location = w.location;
		var parentLocation = w.parent.location;
		if (location.protocol !== parentLocation.protocol || location.hostname !== parentLocation.hostname || location.port !== parentLocation.port) {
			hasDifferentOriginAncestorFlag = true;
			return null;
		}
	} catch (e) {
		hasDifferentOriginAncestorFlag = true;
		return null;
	}

	return w.parent;
}

function findIframeElementInParentWindow(parentWindow:Window, childWindow:Window): HTMLIFrameElement {
	var parentWindowIframes = parentWindow.document.getElementsByTagName('iframe');
	var iframe:HTMLIFrameElement;
	for (var i = 0, len = parentWindowIframes.length; i < len; i++) {
		iframe = parentWindowIframes[i];
		if (iframe.contentWindow === childWindow) {
			return iframe;
		}
	}
	return null;
}

/**
 * Returns a chain of embedded windows with the same origin (which can be accessed programmatically).
 * Having a chain of length 1 might mean that the current execution environment is running outside of an iframe or inside an iframe embedded in a window with a different origin.
 * To distinguish if at one point the current execution environment is running inside a window with a different origin, see hasDifferentOriginAncestor()
 */
export function getSameOriginWindowChain(): IWindowChainElement[] {
	if (!sameOriginWindowChainCache) {
		sameOriginWindowChainCache = [];
		var w = window, parent:Window;
		do {
			parent = getParentWindowIfSameOrigin(w);
			if (parent) {
				sameOriginWindowChainCache.push({
					window: w,
					iframeElement: findIframeElementInParentWindow(parent, w)
				});
			} else {
				sameOriginWindowChainCache.push({
					window: w,
					iframeElement: null
				});
			}
			w = parent;
		} while (w);
	}
	return sameOriginWindowChainCache.slice(0);
}

/**
 * Returns true if the current execution environment is chained in a list of iframes which at one point ends in a window with a different origin.
 * Returns false if the current execution environment is not running inside an iframe or if the entire chain of iframes have the same origin.
 */
export function hasDifferentOriginAncestor(): boolean {
	if (!sameOriginWindowChainCache) {
		getSameOriginWindowChain();
	}
	return hasDifferentOriginAncestorFlag;
}

/**
 * Returns the position of `childWindow` relative to `ancestorWindow`
 */
export function getPositionOfChildWindowRelativeToAncestorWindow(childWindow:Window, ancestorWindow:any) {

	if (!ancestorWindow || childWindow === ancestorWindow) {
		return {
			top: 0,
			left: 0
		};
	}

	var top = 0, left = 0;

	var windowChain = getSameOriginWindowChain();

	for (var i = 0; i < windowChain.length; i++) {
		var windowChainEl = windowChain[i];

		if (windowChainEl.window === ancestorWindow) {
			break;
		}

		if (!windowChainEl.iframeElement) {
			break;
		}

		var boundingRect = windowChainEl.iframeElement.getBoundingClientRect();
		top += boundingRect.top;
		left += boundingRect.left;
	}

	return {
		top: top,
		left: left
	};
}


text:
namespace peloton {
namespace storage {

AbstractTable::AbstractTable(oid_t table_oid, catalog::Schema *schema,
                             bool own_schema)
    : table_oid(table_oid), schema(schema), own_schema_(own_schema) {}

AbstractTable::~AbstractTable() {
  // clean up schema
  if (own_schema_) delete schema;
}

column_map_type AbstractTable::GetTileGroupLayout(
    LayoutType layout_type) const {
  column_map_type column_map;

  auto col_count = schema->GetColumnCount();

  // pure row layout map
  if (layout_type == LAYOUT_TYPE_ROW) {
    for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
      column_map[col_itr] = std::make_pair(0, col_itr);
    }
  }
  // pure column layout map
  else if (layout_type == LAYOUT_TYPE_COLUMN) {
    for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
      column_map[col_itr] = std::make_pair(col_itr, 0);
    }
  }
  // hybrid layout map
  else if (layout_type == LAYOUT_TYPE_HYBRID) {
    for (oid_t col_itr = 0; col_itr < col_count; col_itr++) {
      column_map[col_itr] = std::make_pair(0, col_itr);
    }
  } else {
    throw Exception("Unknown tilegroup layout option : " +
                    std::to_string(layout_type));
  }

  return column_map;
}

TileGroup *AbstractTable::GetTileGroupWithLayout(
    oid_t database_id, oid_t tile_group_id, const column_map_type &partitioning,
    const size_t num_tuples) {
  std::vector<catalog::Schema> schemas;

  // Figure out the columns in each tile in new layout
  std::map<std::pair<oid_t, oid_t>, oid_t> tile_column_map;
  for (auto entry : partitioning) {
    tile_column_map[entry.second] = entry.first;
  }

  // Build the schema tile at a time
  std::map<oid_t, std::vector<catalog::Column>> tile_schemas;
  for (auto entry : tile_column_map) {
    tile_schemas[entry.first.first].push_back(schema->GetColumn(entry.second));
  }
  for (auto entry : tile_schemas) {
    catalog::Schema tile_schema(entry.second);
    schemas.push_back(tile_schema);
  }

  TileGroup *tile_group =
      TileGroupFactory::GetTileGroup(database_id, GetOid(), tile_group_id, this,
                                     schemas, partitioning, num_tuples);

  return tile_group;
}

const std::string AbstractTable::GetInfo() const {
  std::ostringstream inner;
  oid_t tile_group_count = this->GetTileGroupCount();
  oid_t tuple_count = 0;
  for (oid_t tile_group_itr = 0; tile_group_itr < tile_group_count;
       tile_group_itr++) {
    if (tile_group_itr > 0) inner << std::endl;

    auto tile_group = this->GetTileGroup(tile_group_itr);
    auto tile_tuple_count = tile_group->GetNextTupleSlot();

    std::string tileData = tile_group->GetInfo();
    inner << peloton::StringUtil::Prefix(peloton::StringBoxUtil::Box(tileData),
                                         GETINFO_SPACER);
    tuple_count += tile_tuple_count;
  }

  std::ostringstream output;
  output << "Table '" << GetName() << "' [";
  output << "OID= " << GetOid() << ", ";
  output << "NumTuples=" << tuple_count << ", ";
  output << "NumTiles=" << tile_group_count << "]" << std::endl;
  output << inner.str();

  return output.str();
}

}  // namespace storage
}  // namespace peloton

redpajama_set_name: RedPajamaGithub


text:
using JRayXLib.Colors;
using JRayXLib.Shapes;
using JRayXLib.Struct;

namespace JRayXLib.Ray.Tracer
{
    public class BackwardRayTracer
    {
        protected static bool UseOctree = true;
        protected static int MaxRecursionDepth = 100;
        protected Scene.Scene Scene;

        public BackwardRayTracer(Scene.Scene scene)
        {
            Scene = scene;
        }

        public WideColor Shoot(Shapes.Ray ray)
        {
            return ShootRay(ray, 0);
        }

        protected virtual WideColor ShootRay(Shapes.Ray ray, int level)
        {
            if (level == MaxRecursionDepth)
            {
                return Color.Red.ToWide();
            }

            //Find nearest Hit
            CollisionDetails c = Scene.FindNearestHit(ray);

            //No hit
            if (c.Obj == null)
            {
                return Color.White.ToWide();
            }

            //Calculate hit point
            Vect3 hitPoint = ray.Origin + ray.Direction*c.Distance;

            //Return object's color at hit point
            return c.Obj.GetColorAt(hitPoint).ToWide();
        }
    }
}


text:
var request = require('request')
var assert = require('assert')
var tap = require('./tap')
var setup = require('./setup')
var http = require('http')
var parse = require('url').parse

setup(function (req, res) {
  res.end('hello')
}, function (proxy, done) {
  console.log('# hello')
  request.get(proxy, function (err, res, body) {
    tap(assert.equal, 'body is hello')(body, 'hello')
    done()
  })
})

setup(function (req, res) {
  res.end('goodbye')
}, function (proxy, done) {
  console.log('# goodbye')
  request.get(proxy, function (err, res, body) {
    tap(assert.equal, 'body is goodbye')(body, 'goodbye')
    done()
  })
})

setup(function (req, res) {
  req.pipe(process.stderr, {end: false})
//  res.end('goodbye')
//  req.pipe(res)
}, function (proxy, done) {
  console.log('# kill client', parse(proxy))
  var url = parse(proxy)
  url.method = 'post'
  var req = http.request(url)
  console.log('req', req)
/*  req.on('close', function () {
    console.log('request close')
    done()
  })*/
  req.on('response', function (res) {
    res.on('data', console.log)
    .on('end', function () {
      done()
    })
  })
  req.write('a 1\n')
  req.write('a 1\n')
  req.write('a 1\n')
  req.write('a 1\n')
  req.write('a 1\n')
  req.on('error', function (err) {
    console.log('client side error', err)
    done()
  })
  setTimeout(function () {
    req.destroy()
  }, 100)
//  req.end()
})

setup(function (req, res) {
  console.log('# unexpected disconnection')
/*  var i = 0
    , interval = setInterval(function () {
  res.write((i++) + '\n')
  }, 10)*/
  setTimeout(function () {
    console.log('closing server')
//    clearInterval(interval)
    res.destroy()
  }, 122)
}, function (proxy, done) {
  console.log('# test server failure')
  request.get(proxy, function (err, res, body) {
    //this will not produce an error on the proxy
    tap(assert.equal, 'expect ECONNRESET')(err.code, 'ECONNRESET')
    done()
  })
})


text:
ACCEPTED

#### According to
The Catalogue of Life, 3rd January 2011

#### Published in
in Seifert, Mem. N. Y. bot. Gdn 59: 137 (1990)

#### Original name
Arthrobotryum beccarianum Ces., 1879

### Remarks
null


text:
The Errors tab will show the list of errors occurred through the use of the SCRD application. It can
tell you for example the number of failed calculations version or the number of failed payment
addition to an account.

ErrorsLog.


text:
An implementation of Core Data Helper origin from Textbook: 《Learning Core Data for iOS》.

## Installation:

### Pod

```ruby
pod 'CKCoreDataHelper'
```

## Usage:

### Core Data Setup

```objc
// Your database file name
NSString *storeFileName = @"test.sqlite";

// Initialized a core data manager
CKCoreDataManager *manager = [CKCoreDataManager sharedInstanced];

// Setup core data manager with given store file
NSError *error;
BOOL flag = [manager setupCoreDataWithStoreFileName:storeFileName // Store file name
                               lightWeightMigration:YES           // enable lightweight data migration
                                              error:&error];      // get the error if init failed
```

### Import data

There are two importer you can use to import data into persistent store. One for XML format, another for JSON format.

#### XML

```objc
// Initialize
_importer = [[CKCoreDataXMLImporter alloc]
                 initWithCoordinator:self.manager.coordinator
                 entitiesUniqueAttributes:@{@"Product": @"name",
                                            @"Shop": @"name"}];

NSURL *productXML = [bundle URLForResource:@"preload_product" withExtension:@"xml"];

[_importer importDataFrom:shopXML                                         // XML URL Path
                forEntity:@"Shop"                                         // The name for the Entity you need to import to
               completion:^(BOOL success, NSError * _Nullable error) {    // A callback when import finished.
                   XCTAssertTrue(success);
                   XCTAssertNil(error);
               }];
```

### JSON
```objc

// Initialize
_importer = [[CKCoreDataJSONImporter alloc]
                 initWithCoordinator:self.manager.coordinator
                 entitiesUniqueAttributes:@{@"Product": @"name",
                                            @"Shop": @"name"}];

NSURL *path = [bundle URLForResource:@"preload_product_withoutrel" withExtension:@"json"];

[_importer importDataFrom:path
                forEntity:@"Product"
               completion:^(BOOL success, NSError * _Nullable error) {
                   XCTAssertTrue(success);
                   XCTAssertNil(error);
               }];
```

## Entity CURD

### Retrieve record

```objc
NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"Entity"];
NSArray *results = [_manager.context executeFetchRequest:fetchRequest error:nil];
```

### Sorting

```objc
NSSortDescriptor *sort = [NSSortDescriptor sortDescriptorWithKey:@"attribute Name" ascending:YES];
[fetchRequest setSortDescriptors:@[sort]];
```

### Filter (Using NSPredicate). [NSPredicate manual](https://developer.apple.com/library/content/documentation/Cocoa/Conceptual/Predicates/AdditionalChapters/Introduction.html#//apple_ref/doc/uid/TP40001789)

```objc
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF.name == %@", @"Enix"];
[fetchRequest setPredicate:predicate];
```

### Filter (Fetch Request Template)

1. Select Model.xcdatamodeld
2. Editor > Add Fetch Request
3. Set a name for your fetch request,eg, fetchByName
4. Add filtering expression
5. Get your fetch request template in code:

```objc
NSFetchRequest *req = [[_manager model]
                       fetchRequestTemplateForName:@"your fetch request name"];
```

### Create Entity instance

```objc
Entity *newItem = [NSEntityDescription insertNewObjectForEntityForName:@"Entity"
                                                inManagedObjectContext:context];
```

### Delete record

```objc
// Get the record which is pending to remove
NSArray *results = [[coreDataHelper context] executeFetchRequest:fetchRequest error:nil];

// Delete the record
[[_manager context] deleteObject:[results firstObject]];
```

### Save

```objc
NSError *error = nil;
[context save:&error];
```


text:
<?php

namespace Chromabits\Illuminated\Auth;

use Chromabits\Nucleus\Support\Enum;

/**
 * Class KeyPairTypes.
 *
 * Some common types of key pairs.
 *
 * @author Eduardo Trujillo <ed@chromabits.com>
 * @package Chromabits\Illuminated\Auth
 */
class KeyPairTypes extends Enum
{
    const TYPE_HMAC = 'hmac';
    const TYPE_GENERIC = 'generic';
}


text:
package org.telegram.bot.messaging;

import org.telegram.bot.util.concurrent.TimeProperty;

import java.util.Iterator;
import java.util.List;

/**
 * @author ahmad
 */
public interface MessageQueue {

    boolean add(Message message);

    boolean addAll(List<Message> messages);

    Message poll();

    Message poll(TimeProperty timeout);

    Message take();

    Iterator<Message> iterator();

    List<Message> removeAll();

    void stop(Message stopMessage);

}


text:
package fixtures.http;

import com.microsoft.rest.ServiceResponseWithHeaders;

import org.junit.Assert;
import org.junit.BeforeClass;
import org.junit.Ignore;
import org.junit.Test;

import java.util.List;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;

import fixtures.http.implementation.AutoRestHttpInfrastructureTestServiceImpl;
import fixtures.http.models.HttpRedirectsDelete307Headers;
import fixtures.http.models.HttpRedirectsGet300Headers;
import fixtures.http.models.HttpRedirectsGet301Headers;
import fixtures.http.models.HttpRedirectsGet302Headers;
import fixtures.http.models.HttpRedirectsGet307Headers;
import fixtures.http.models.HttpRedirectsHead300Headers;
import fixtures.http.models.HttpRedirectsHead301Headers;
import fixtures.http.models.HttpRedirectsHead302Headers;
import fixtures.http.models.HttpRedirectsHead307Headers;
import fixtures.http.models.HttpRedirectsPatch302Headers;
import fixtures.http.models.HttpRedirectsPatch307Headers;
import fixtures.http.models.HttpRedirectsPost303Headers;
import fixtures.http.models.HttpRedirectsPost307Headers;
import fixtures.http.models.HttpRedirectsPut301Headers;
import fixtures.http.models.HttpRedirectsPut307Headers;
import rx.functions.Action1;

public class HttpRedirectsTests {
    private static AutoRestHttpInfrastructureTestService client;
    private CountDownLatch lock = new CountDownLatch(1);

    @BeforeClass
    public static void setup() {
        client = new AutoRestHttpInfrastructureTestServiceImpl("http://localhost:3000");
    }

    @Test
    public void head300() throws Exception {
        client.httpRedirects().head300WithServiceResponseAsync()
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsHead300Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsHead300Headers> response) {
                    Assert.assertEquals(200, response.getHeadResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(100000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void get300() throws Exception {
        client.httpRedirects().get300WithServiceResponseAsync()
            .subscribe(new Action1<ServiceResponseWithHeaders<List<String>, HttpRedirectsGet300Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<List<String>, HttpRedirectsGet300Headers> response) {
                    Assert.assertEquals(200, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void head301() throws Exception {
        client.httpRedirects().head301WithServiceResponseAsync()
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsHead301Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsHead301Headers> response) {
                    Assert.assertEquals(200, response.getHeadResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void get301() throws Exception {
        client.httpRedirects().get301WithServiceResponseAsync()
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsGet301Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsGet301Headers> response) {
                    Assert.assertEquals(200, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    @Ignore("Not supported yet")
    public void put301() throws Exception {
        client.httpRedirects().put301WithServiceResponseAsync()
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsPut301Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsPut301Headers> response) {
                    Assert.assertEquals(301, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void head302() throws Exception {
        client.httpRedirects().head302WithServiceResponseAsync()
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsHead302Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsHead302Headers> response) {
                    Assert.assertEquals(200, response.getHeadResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void get302() throws Exception {
        client.httpRedirects().get302WithServiceResponseAsync()
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsGet302Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsGet302Headers> response) {
                    Assert.assertEquals(200, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    @Ignore("Not supported yet")
    public void patch302() throws Exception {
        client.httpRedirects().patch302WithServiceResponseAsync(true)
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsPatch302Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsPatch302Headers> response) {
                    Assert.assertEquals(302, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void post303() throws Exception {
        client.httpRedirects().post303WithServiceResponseAsync(true)
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsPost303Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsPost303Headers> response) {
                    Assert.assertEquals(200, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void head307() throws Exception {
        client.httpRedirects().head307WithServiceResponseAsync()
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsHead307Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsHead307Headers> response) {
                    Assert.assertEquals(200, response.getHeadResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void get307() throws Exception {
        client.httpRedirects().get307WithServiceResponseAsync()
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsGet307Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsGet307Headers> response) {
                    Assert.assertEquals(200, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void put307() throws Exception {
        client.httpRedirects().put307WithServiceResponseAsync(true)
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsPut307Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsPut307Headers> response) {
                    Assert.assertEquals(307, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void patch307() throws Exception {
        client.httpRedirects().patch307WithServiceResponseAsync(true)
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsPatch307Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsPatch307Headers> response) {
                    Assert.assertEquals(307, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void post307() throws Exception {
        client.httpRedirects().post307WithServiceResponseAsync(true)
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsPost307Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsPost307Headers> response) {
                    Assert.assertEquals(307, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }

    @Test
    public void delete307() throws Exception {
        client.httpRedirects().delete307WithServiceResponseAsync(true)
            .subscribe(new Action1<ServiceResponseWithHeaders<Void, HttpRedirectsDelete307Headers>>() {
                @Override
                public void call(ServiceResponseWithHeaders<Void, HttpRedirectsDelete307Headers> response) {
                    Assert.assertEquals(307, response.getResponse().code());
                    lock.countDown();
                }
            });
        Assert.assertTrue(lock.await(1000, TimeUnit.MILLISECONDS));
    }
}


text:
#import "Month.h"

@interface Month ()

// Private interface goes here.

@end

@implementation Month

// Custom logic goes here.

@end


text:
import {Component,} from "@angular/core";
import {NS_ROUTER_DIRECTIVES} from "nativescript-angular/router";
import {TalkService} from "./shared/talks/talk.service";

@Component({
    selector: "main",
    directives: [NS_ROUTER_DIRECTIVES],
    providers: [TalkService],
    template: `<page-router-outlet></page-router-outlet>`,
})
export class AppComponent {
 }


text:
@interface SSPersonHeaderView : UIView {

	BOOL _alignImageToLeft;
	BOOL _organization;
	UIImageView *_imageView;
	NSString *_personName;
	NSString *_organizationName;
}

@property (nonatomic, assign, getter=isOrganization) BOOL organization;
@property (nonatomic, assign) BOOL alignImageToLeft;
@property (nonatomic, retain, readonly) UIImageView *imageView;

@property (nonatomic, retain) UIImage *image;
@property (nonatomic, copy) NSString *personName;
@property (nonatomic, copy) NSString *organizationName;

@end


text:
var SINGLE_COPY = 'SINGLE_COPY'

function cp (env, args) {
  // Ignore command name
  args.shift()

  var rFlagIndex = args.findIndex(function (arg) {
    return arg === '-r' || arg === '-R'
  })
  var isRecursive = rFlagIndex !== -1
  if (isRecursive) {
    args.splice(rFlagIndex, 1)
  }

  if (!args.length) {
    env.error('cp: missing file operand')
    env.exit(1)
    return
  }
  if (args.length === 1) {
    env.error('cp: missing destination file operand after '' + args[0] + ''')
    env.exit(1)
    return
  }

  var destination = args[args.length - 1]
  var files = args.slice(0, -1)

  function copy (file, dest) {
    return env.system.stat(file).then(function (stats) {
      if (stats.type === 'dir' && !isRecursive) {
        return Promise.reject('cp: omitting directory '' + file + ''')
      }
      return env.system.copy(file, dest)
    })
  }

  env.system.stat(destination)
    .then(function (stats) {
      if (stats.type !== 'dir') {
        return Promise.reject()
      }
    })
    .catch(function () {
      if (files.length !== 1) {
        return Promise.reject('cp: target '' + destination + '' is not a directory')
      }
      return SINGLE_COPY
    })
    .then(function (actionType) {
      if (actionType === SINGLE_COPY) {
        return copy(files[0], destination)
      }
      return Promise.all(files.map(function (file) {
        var filePathParts = file.split('/')
        var fileName = filePathParts[filePathParts.length - 1]
        var dest = destination + '/' + fileName
        return copy(file, dest)
      }))
    })
    .then(function () {
      env.exit(0)
    })
    .catch(function (err) {
      env.error(err)
      env.exit(1)
    })
}

module.exports = cp


text:
package loaders

import (
	"fmt"
	"net/url"
	"os"

	"github.com/rehabstudio/oneill/containerdefs"
)

// GetLoader parses a given URI and returns an appropriate loader. For now
// this always returns our default (and only) loader, but could be easily
// expanded to load container definitions from a remote location, or from a
// single file.
func GetLoader(uriStr string) (containerdefs.DefinitionLoader, error) {

	// parse uri so we can decide which loader to use
	uri, err := url.Parse(uriStr)
	if err != nil {
		return &LoaderDirectory{rootDirectory: ""}, err
	}

	// return an appropriate file or directory loader
	if uri.Scheme == "file" {
		// check if path exists
		src, err := os.Stat(uri.Path)
		if err != nil {
			return &LoaderDirectory{rootDirectory: ""}, err
		}
		// check if path is a single file or a directory
		if src.IsDir() {
			return &LoaderDirectory{rootDirectory: uri.Path}, nil
		} else {
			return &LoaderFile{path: uri.Path}, nil
		}
	}

	// return the http loader
	if uri.Scheme == "http" || uri.Scheme == "https" {
		return &LoaderURL{url: uriStr}, nil
	}

	// return the http loader
	if uri.Scheme == "stdin" {
		return &LoaderStdin{}, nil
	}

	// couldn't find a loader, return an error :(
	err = fmt.Errorf("Unable find matching loader for definitions uri: %s", uriStr)
	return &LoaderDirectory{rootDirectory: ""}, err
}


text:
.mdl-button {
  background-color: #E91E63;
}
.mdl-button:hover,
.mdl-button:focus {
  background-color: #E91E63;
}
.mdl-button--fab {
  background-color: #E91E63;
}
.mdl-button--fab:focus:not(:active) {
  background-color: #E91E63;
}
.mdl-button--search {
  background-color: transparent;
}
.mdl-button--search:hover {
  background-color: transparent;
}
.site-navbar .site-nav ul li.dropdown-item ul.dropdown-menu li:hover > a {
  color: #E91E63;
}
.site-navbar .site-nav ul li.dropdown-item ul.dropdown-menu li.dropdown-item:hover > a {
  color: #E91E63;
}
.site-navbar .site-nav ul li.dropdown-item ul.dropdown-menu li.dropdown-item:hover > a:after {
  color: #E91E63;
}
.site-navbar .site-nav ul li:hover > a {
  color: #E91E63;
}
.site-navbar .site-nav .cl-effect-5 > li.active > a {
  color: #E91E63;
}
.mobile-menu-trigger .hamburger-inner,
.mobile-menu-trigger .hamburger-inner::before,
.mobile-menu-trigger .hamburger-inner::after {
  background-color: #E91E63;
}
.mobile-menu > ul li a:hover {
  color: #E91E63;
  border-left: 4px solid #E91E63;
}
.mobile-menu > ul li a:hover i {
  color: #E91E63;
}
.mobile-menu > ul li.active a {
  color: #E91E63;
  border-left-color: #E91E63;
}
.mobile-menu > ul li.active a i {
  color: #E91E63;
}
.mobile-menu > ul li.dropdown-item:hover > a {
  color: #E91E63;
}
.mobile-menu > ul li.dropdown-item:hover > a:after {
  color: #E91E63;
}
.mobile-menu__footer ul li a i:hover {
  color: #E91E63;
}
.section-heading h3 a {
  color: #E91E63;
}
.services .single-service i {
  color: #E91E63;
}
.services .single-service:hover {
  background-color: #E91E63;
}
.search-bar .mdl-textfield .mdl-textfield__input {
  border: 1px solid #E91E63;
}
.portfolio .portfolio-category-wrap ul.portfolio-category li:hover {
  color: #E91E63;
}
.portfolio .portfolio-category-wrap ul.portfolio-category li.active {
  color: #E91E63;
  border-bottom-color: #E91E63;
}
.portfolio .protfolio-items .portfolio-item a:after {
  background-color: rgba(233, 30, 99, 0.85);
}
.shot-count-inner button:active,
.shot-count-inner button:focus {
  background: #E91E63;
}
.shot-count-inner .mdl-button--fab:focus:not(:active),
.shot-count-inner .mdl-button:focus:not(:active) {
  background: #E91E63;
}
.prev-header .pre-close a i:hover {
  color: #E91E63;
}
.share .mdl-button--fab {
  background-color: #E91E63;
}
.team .member .member__info__skills ul li .progress-bar__active {
  background-color: #E91E63;
}
.team .member .member__info__social li a i:hover {
  color: #E91E63;
}
.skills {
  background-color: #E91E63;
}
.skills .skill-slider .single-skill i {
  color: #E91E63;
}
.skills .skill-slider .single-skill .progress-bar__bar__active {
  background-color: #E91E63;
}
.resume .mdl-tabs .mdl-tabs__panel .card .card__header .card__header__left .card__header__left__icon {
  background-color: #E91E63;
}
.resume .mdl-tabs .mdl-tabs__panel .card .card__header .card__header__left .card__header__left__text h4 {
  color: #E91E63;
}
.mdl-tabs.is-upgraded .mdl-tabs__tab.is-active {
  color: #E91E63;
}
.mdl-tabs.is-upgraded .mdl-tabs__tab.is-active:after {
  background: #E91E63;
}
.mdl-tabs__tab-bar .mdl-tabs__tab:hover {
  color: #E91E63;
}
.post-thumb-slider .owl-dots .owl-dot.active {
  background: #E91E63;
}
.mdl-card__title-text a:hover {
  color: #E91E63;
}
.mdl-card__actions.mdl-card--border a.blog-comments:hover {
  color: #E91E63;
}
.mdl-card__actions.mdl-card--border a.blog-share:hover {
  color: #E91E63;
}
.single-blog-post-content blockquote {
  border-left: 5px solid #E91E63;
}
.single-blog-post-content ul.list li:before {
  background-color: #E91E63;
}
.single-blog-post-content__share__icons ul li a:hover {
  color: #E91E63;
}
.single-blog-post-content__comments ul li .single-blog-post-content__comments__comment__text__top__right a {
  color: #E91E63;
}
.sidebar__widget ul li a:hover {
  color: #E91E63;
}
.sidebar__widget.sidebar__widget--tags ul li a:hover {
  background-color: #E91E63;
  color: #fff;
}
.page-about__technical-skills__inner-bar ul li .progress-bar__active {
  background-color: #E91E63;
}
.page-about__service__single__icon i {
  color: #E91E63;
}
.portfolio-navigation ul li a i:hover {
  color: #E91E63;
}
.banner__content--2 .banner__content__text ul li a:hover {
  color: #E91E63;
}
.banner__content--2 .banner__content__navigation ul li a i:hover {
  color: #E91E63;
}
.contact-address .single-address__icon i {
  color: #E91E63;
}
.mdl-textfield__input:focus {
  border-color: #E91E63;
}
.map__buttons {
  background-color: rgba(233, 30, 99, 0.94);
}
.map__buttons:hover {
  background-color: rgba(233, 30, 99, 0.7);
}
.portfolio-spec__single p a {
  color: #E91E63;
}
.portfolio-spec__single ul li a:hover i {
  color: #E91E63;
}
.testimonial .testimonial-slider .single-testimonial h4 {
  color: #E91E63;
}
.footer__top__inner ul li a i:hover {
  color: #E91E63;
}
.mfp-close:hover {
  color: #E91E63;
}
.zmdi-chevron-left.mfp-prevent-close:hover,
.zmdi-chevron-right.mfp-prevent-close:hover {
  background: #E91E63;
}
.owl-carousel .owl-nav .mdl-button--fab:hover {
  background: #E91E63;
}
.owl-carousel .owl-dots .owl-dot.active {
  background: #E91E63;
}
.page-about__content__inner-slider .owl-nav .mdl-button--fab:hover,
.portfolio-slider .owl-nav .mdl-button--fab:hover {
  background: #E91E63;
}
.portfolio-slider.owl-carousel .owl-dots .owl-dot:hover,
.portfolio-slider.owl-carousel .owl-dots .owl-dot.active {
  background: #E91E63;
}
.footer2 .single-column ul li a:hover {
  color: #E91E63;
}
.footer2 .single-column .footer2__social li:hover a i {
  color: #E91E63;
}
.sweet-alert button {
  background-color: #E91E63 !important;
}
.skill-slider .owl-nav .mdl-button--fab:hover {
  background: rgba(0, 0, 0, 0.14);
}
.personx-option-panel-box .personx-option-panel-toggle {
  color: #E91E63;
}


text:
package org.openntf.domino.graph2.builtin;

import org.openntf.domino.graph2.impl.DElementStore;

public class EditStore extends DElementStore {

	public EditStore() {
		this.addType(Edits.class);
		this.addType(Editable.class);
	}

}


text:
<?php defined('BASEPATH') OR exit('No direct script access allowed');

// labels
$lang['redirects:from'] 			    = 'Vanaf';
$lang['redirects:to']					= 'Naar';
$lang['redirects:edit']					= 'Wijzig';
$lang['redirects:delete']				= 'Verwijder';
$lang['redirects:type']					= 'Type';

// redirect types
$lang['redirects:301']					= '301 - Permanent verplaatst';
$lang['redirects:302']					= '302 - Tijdelijk verplaatst';

// titles
$lang['redirects:add_title'] 			= 'Voeg verwijzing toe';
$lang['redirects:edit_title'] 			= 'Wijzig verwijzing';
$lang['redirects:list_title'] 			= 'Overzicht verwijzingen';

// messages
$lang['redirects:no_redirects']			= 'Er zijn geen verwijzingen.';
$lang['redirects:add_success'] 			= 'De verwijzing is toegevoegd.';
$lang['redirects:add_error'] 			= 'De verwijzing kon niet worden toegevoegd. Probeer het later nogmaals.';
$lang['redirects:edit_success'] 		= 'De verwijzing is opgeslagen.';
$lang['redirects:edit_error'] 			= 'De verwijzing kon niet worden opgeslagen. Probeer het later nogmaals.';
$lang['redirects:mass_delete_error'] 	= 'Fout tijdens het verwijderen van verwijzing "%s".';
$lang['redirects:mass_delete_success']	= '%s verwijzingen van %s verwijderd.';
$lang['redirects:no_select_error'] 		= 'U moet een verwijzing selecteren om te kunnen verwijderen.';
$lang['redirects:request_conflict_error']	= 'Er bestaat al een verwijzing vanaf "%s".';


text:
.. _devsetup:

================================
Getting Started with Development
================================

.. Note:: If you have just started, this may seem confusing, and that is okay.
   No one starts out understanding how to do all of this. Additionally, anything that is
   confusing is a bug in our docs. Please open an issue to let us know where we
   need to improve things.

Ready to contribute code? Here's how to set up `ResearchCompendia` for local
development.

Getting Code
------------

Fork the repository and check out your fork and add our repo as a remote::

   $ git clone https://github.com/YOURACCOUNT/researchcompendia.git
   $ cd researchcompendia
   $ git remote add parent https://github.com/researchcompendia/researchcompendia.git

Installing Dependencies
-----------------------

1. Install your local copy into a virtualenv. Here is one way to do it::

    $ cd researchcompendia/
    $ virtualenv venv
    $ source venv/bin/activate
    $ pip install -r requirements/ci.txt

   You can also use `virtualenvwrapper
   <http://virtualenvwrapper.readthedocs.org/en/latest/>`_ if you have it is
   installed. It is convenient, though not required.

2. Set up environment variables. Once you have the environment varialbes set up, you are ready to
   set up the database.

3. We use Postgres as our database backend. We haven't written docs to
   walk though setting up Postgres yet. If you are unfamiliar with this
   process, you could consider using sqlite locally event thought our
   preferences is to use postgres in all environments. If you'd like to use
   sqlite, set up your DATABASE_URL environment variable to have a path to
   a file name that will hold your database. for example::

     'sqlite:////path/to/my/site/root/researchcompendia.db'

Setting up the Environment
--------------------------

These are the environment variables that are used in the site settings listed along with their defaults.
For any default that doesn't apply to you, make an environment variable with your preferred setting.

You are required to create SECRET_KEY environment variable.

If you use fabric to provision a vagrant box,
it will generate a SECRET_KEY for you.

  =================================  ===========================================================================
  Environment Variable               Default Setting
  =================================  ===========================================================================
  ADMINS                             compendia@example.com
  AWS_ACCESS_KEY_ID                  ''
  AWS_SECRET_ACCESS_KEY              ''
  AWS_STORAGE_BUCKET_NAME            compendiaexamplebucket
  DATABASE_URL                       postgres://:5432/researchcompendia
  DJANGO_BROKER_URL                  hamqp://guest:guest@localhost:5672//
  DJANGO_CELERY_DISABLE_RATE_LIMITS  True
  DJANGO_CELERY_RESULT_BACKEND       cache+memcached://127.0.0.1:11211/
  DJANGO_CELERY_RESULT_SERIALIZER    json
  DJANGO_CELERY_TASK_SERIALIZER      json
  DJANGO_CELERY_TIMEZONE             US/Central
  CROSSREF_PID                       ''
  DEBUG                              True
  DEFAULT_FILE_STORAGE               django.core.files.storage.FileSystemStorage
  DEFAULT_FROM_EMAIL                 compendia@example.com
  DISQUS_API_KEY                     'none'
  DISQUS_WEBSITE_SHORTNAME           researchcompendiaorg
  BONSAI_URL                         http://127.0.0.1:9200
  EMAIL_BACKEND                      django.core.mail.backends.console.EmailBackend
  MAILGUN_ACCESS_KEY                 ''
  MAILGUN_SERVER_NAME                ''
  MEDIA_ROOT                         normpath(join(PROJECT_ROOT, 'media'))
  MEDIA_URL                          if using the s3boto storages then '%s/media/' % S3_URL, otherwise /media/
  REMOTE_DEBUG                       False
  SECRET_KEY                         no default. will blow up if not set
  SITE_ID                            1
  STATICFILES_STORAGE                django.contrib.staticfiles.storage.StaticFilesStorage
  STATIC_ROOT                        normpath(join(PROJECT_ROOT, 'staticfiles'))
  STATIC_URL                         if using the s3boto storages then '%s/static/' % S3_URL, otherwise /static/
  =================================  ===========================================================================

There are a couple of places where settings are hard-coded in to templates. These need to be fixed. Meanwhile,
you will need to change or remove the google analytics and addthis pubid codes.

* Our google analytics tracking code is hardcoded in templates/base.html.
* Our addthis pubid is hardcoded in templates/compendia/detail.html.

Preparing the Database
----------------------

Set up the database by running::

   $ cd companionpages
   $ ./manage.py syncdb --migrate
   $ ./manage.py loaddata fixtures/*

Launching ResearchCompendia
---------------------------

Once the database is set up, you can start the app::

    $ ./manage.py runserver

Or perhaps you would like to have detailed stacktraces and messages::

    $ ./manage.py runserver --traceback -v 3

Making Changes
--------------

Now that you have the code, a virtualenv, and the proper environment variables, you are ready to make your changes locally.

1. Make a topic branch for your changes. For example, if you wanted to add twitter logins to the site, you could make a branch named *twitterlogin*::

   $ git checkout -b twitterlogin

2. Periodically update your branch from the parent develop branch. Use git rebase (not git merge)::

    $ git fetch parent
    $ git rebase parent/develop

   We prefer a pull request with one commit rather than many small commits.
   To avoid making a request with many commits, you can do an `interactive rebase
   <https://help.github.com/articles/interactive-rebase>`_ and use fixup.::

    $ git rebase -i parent/develop

3. Check that your changes pass style check and automated tests::

    $ make test

4. Demonstrate your changes. It can be helpful to share work you are running locally from your own machine so that other people can help test.  `PageKite <https://pagekite.net/>`_ is a free/libre open source software project that can do this for you. This `QuickStart <http://pagekite.net/support/quickstart/>`_ shows how.

5. Commit your changes and push your branch to up to your fork on GitHub.::

    $ git add .
    $ git commit -m "Adds twitter login for #123"
    $ git push origin twitterlogin

Now you are ready to make a pull request.

Reviewing Changes
-----------------

Submit a pull request through the GitHub website to submit it for review.
Before you submit a pull request, check that it meets these guidelines:

  0. The pull request should be easy to review.
  1. The pull request should include tests
  2. Check https://travis-ci.org/researchcompendia/researchcompendia/pull_requests
     and make sure that the tests pass
  3. If the pull request adds functionality, the docs and/or comments should be updated.

Trying out Vagrant
------------------

.. Note:: This section is for developers who have experience with Vagrant and Fabric

If you want to use Vagrant clone the `researchcompendia-deployment
<https://github.com/researchcompendia/researchcompendia-deployment>`_ repo. It
contains fabric files and a Vagrantfile that pulls down a debian wheezy VM from
vagrantcound::

    $ git clone https://github.com/researchcompendia/researchcompendia-deployment.git
    $ cd researchcompendia-deployment
    $ vagrant up
    $ fab vagrant provision

Provision is not idempotent, so running it twice will probably fail in interesting ways.
If you want to start over need to run `vagrant destroy` first.

Provision will set up the vagrant box in the same way that a production box is set up.


text:
package org.jboss.as.quickstarts.tasks;

import org.jboss.shrinkwrap.api.ShrinkWrap;
import org.jboss.shrinkwrap.api.asset.EmptyAsset;
import org.jboss.shrinkwrap.api.spec.WebArchive;

public class DefaultDeployment {

    public static WebArchive deployment() {
        return ShrinkWrap.create(WebArchive.class, "test.war")
                 .addPackages(true, Task.class.getPackage().getName())
                .addAsResource("META-INF/test-persistence.xml", "META-INF/persistence.xml")
                .addAsWebInfResource("test-ds.xml", "test-ds.xml")
                .addAsWebInfResource(EmptyAsset.INSTANCE, "beans.xml")
                .addAsResource("import.sql");
    }

}


text:
teststring="blah blah blah"

for interpreter in python python3; do
    for pastebin in $($interpreter pastebinit -l | egrep "^-" | sed "s/^- //g")
    do
        echo "Trying http://$pastebin ($interpreter)"
        URL=$(echo "$teststring\n$teststring\n$teststring" | $interpreter pastebinit -b http://$pastebin)

        if [ "$pastebin" = "paste.ubuntu.org.cn" ]; then
            out=$(wget -O - -q "$URL" | gzip -d | grep "$teststring")
        else
            out=$(wget -O - -q "$URL" | grep "$teststring")
        fi

        if [ -n "$out" ]; then
            echo "PASS: http://$pastebin ($URL) ($interpreter)"
        else
            echo "FAIL: http://$pastebin ($URL) ($interpreter)"
        fi
        echo ""
    done
done


text:
<?php

/**
 * acDompdfPluginConfiguration represents the configuration for acDompdfPlugin plugin.
 *
 * @package    acDompdfPlugin
 * @subpackage config
 * @author     Jean-Baptiste Le Metayer <lemetayer.jb@gmail.com>
 * @author     Vincent Laurent <vince.laurent@gmail.com>
 * @version    0.1
 */
class acDompdfPluginConfiguration extends sfPluginConfiguration
{
  /**
   * Initializes acDompdfPlugin.
   *
   *
   * @access public
   *
   */
  public function initialize()
  {
  	require_once(dirname(__FILE__).'/../lib/vendor/dompdf/dompdf_config.inc.php');
    sfConfig::set('sf_autoloading_functions', array(array('acDompdfBridge', 'autoload')));
  }
}


text:
import time
import random
from test_framework.test_framework import BitcoinTestFramework
from test_framework.util import assert_equal
from test_framework.util import *
from test_framework.blocktools import *
import test_framework.script as script
import pdb
import sys
if sys.version_info[0] < 3:
    raise "Use Python 3"
import logging
logging.basicConfig(format='%(asctime)s.%(levelname)s: %(message)s', level=logging.INFO, stream=sys.stdout)

def mostly_sync_mempools(rpc_connections, difference=50, wait=1, verbose=1):
    """
    Wait until everybody has the most of the same transactions in their memory
    pools. There is no guarantee that mempools will ever sync due to the
    filterInventoryKnown bloom filter.
    """
    iterations = 0
    while True:
        iterations += 1
        pool = set(rpc_connections[0].getrawmempool())
        num_match = 1
        poolLen = [len(pool)]
        for i in range(1, len(rpc_connections)):
            tmp = set(rpc_connections[i].getrawmempool())
            if tmp == pool:
                num_match = num_match + 1
            if iterations > 10 and len(tmp.symmetric_difference(pool)) < difference:
                num_match = num_match + 1
            poolLen.append(len(tmp))
        if verbose:
            logging.info("sync mempool: " + str(poolLen))
        if num_match == len(rpc_connections):
            break
        time.sleep(wait)

class ExcessiveBlockTest (BitcoinTestFramework):
    def __init__(self, extended=False):
        self.extended = extended
        BitcoinTestFramework.__init__(self)

    def setup_network(self, split=False):
        self.nodes = []
        self.nodes.append(start_node(0, self.options.tmpdir, ["-rpcservertimeout=0"], timewait=60 * 10))
        self.nodes.append(start_node(1, self.options.tmpdir, ["-rpcservertimeout=0"], timewait=60 * 10))
        self.nodes.append(start_node(2, self.options.tmpdir, ["-rpcservertimeout=0"], timewait=60 * 10))
        self.nodes.append(start_node(3, self.options.tmpdir, ["-rpcservertimeout=0"], timewait=60 * 10))
        interconnect_nodes(self.nodes)
        self.is_network_split = False
        self.sync_all()

        if 0:  # getnewaddress can be painfully slow.  This bit of code can be used to during development to
               # create a wallet with lots of addresses, which then can be used in subsequent runs of the test.
               # It is left here for developers to manually enable.
            TEST_SIZE = 100  # TMP 00
            print("Creating addresses...")
            self.nodes[0].keypoolrefill(TEST_SIZE + 1)
            addrs = [self.nodes[0].getnewaddress() for _ in range(TEST_SIZE + 1)]
            with open("walletAddrs.json", "w") as f:
                f.write(str(addrs))
                pdb.set_trace()

    def run_test(self):
        BitcoinTestFramework.run_test(self)
        self.testCli()
        self.testExcessiveSigops()

        # clear out the mempool
        mostly_sync_mempools(self.nodes)
        for n in self.nodes:
            n.generate(2)
            sync_blocks(self.nodes)
        for n in self.nodes:
            while len(n.getrawmempool()):
                n.generate(1)
                sync_blocks(self.nodes)
        logging.info("cleared mempool: %s" % str([len(x) for x in [y.getrawmempool() for y in self.nodes]]))
        self.testExcessiveBlockSize()
        self.testExcessiveTx()

    def testCli(self):

        # Assumes the default excessive at 16MB and mining at 1MB
        try:
            self.nodes[0].setminingmaxblock(32000000)
        except JSONRPCException as e:
            pass
        else:
            assert(0)  # was able to set the mining size > the excessive size

        try:
            self.nodes[0].setminingmaxblock(99)
        except JSONRPCException as e:
            pass
        else:
            assert(0)  # was able to set the mining size below our arbitrary minimum

        try:
            self.nodes[0].setexcessiveblock(1000, 10)
        except JSONRPCException as e:
            pass
        else:
            assert(0)  # was able to set the excessive size < the mining size

    def sync_all(self):
        """Synchronizes blocks and mempools (mempools may never fully sync)"""
        if self.is_network_split:
            sync_blocks(self.nodes[:2])
            sync_blocks(self.nodes[2:])
            mostly_sync_mempools(self.nodes[:2])
            mostly_sync_mempools(self.nodes[2:])
        else:
            sync_blocks(self.nodes)
            mostly_sync_mempools(self.nodes)

    def createUtxos(self, node, addrs, amt):
        wallet = node.listunspent()
        wallet.sort(key=lambda x: x["amount"], reverse=True)

        # Create a LOT of UTXOs
        logging.info("Create lots of UTXOs...")
        n = 0
        group = min(100, amt)
        count = 0
        for w in wallet:
            count += group
            split_transaction(node, [w], addrs[n:group + n])
            n += group
            if n >= len(addrs):
                n = 0
            if count > amt:
                break
        self.sync_all()
        logging.info("mine blocks")
        node.generate(1)  # mine all the created transactions
        logging.info("sync all blocks and mempools")
        self.sync_all()

    def expectHeights(self, blockHeights, waittime=10):
        loop = 0
        count = []
        while loop < waittime:
            counts = [x.getblockcount() for x in self.nodes]
            if counts == blockHeights:
                return True  # success!
            time.sleep(1)
            loop += 1
            if ((loop % 30) == 0):
                logging.info("...waiting %s" % loop)
        return False

    def generateTx(self, node, txBytes, addrs, data=None):
        wallet = node.listunspent()
        wallet.sort(key=lambda x: x["amount"], reverse=False)
        logging.info("Wallet length is %d" % len(wallet))

        size = 0
        count = 0
        decContext = decimal.getcontext().prec
        decimal.getcontext().prec = 8 + 8  # 8 digits to get to 21million, and each bitcoin is 100 million satoshis
        while size < txBytes:
            count += 1
            utxo = wallet.pop()
            outp = {}
            # Make the tx bigger by adding addtl outputs so it validates faster
            payamt = satoshi_round(utxo["amount"] / decimal.Decimal(8.0))
            for x in range(0, 8):
                # its test code, I don't care if rounding error is folded into the fee
                outp[addrs[(count + x) % len(addrs)]] = payamt
                #outscript = self.wastefulOutput(addrs[(count+x)%len(addrs)])
                #outscripthex = hexlify(outscript).decode("ascii")
                #outp[outscripthex] = payamt
            if data:
                outp["data"] = data
            txn = createrawtransaction([utxo], outp, createWastefulOutput)
            # txn2 = node.createrawtransaction([utxo], outp)
            signedtxn = node.signrawtransaction(txn)
            size += len(binascii.unhexlify(signedtxn["hex"]))
            node.sendrawtransaction(signedtxn["hex"])
        logging.info("%d tx %d length" % (count, size))
        decimal.getcontext().prec = decContext
        return (count, size)

    def testExcessiveSigops(self):
        """This test checks the behavior of the nodes in the presence of transactions that take a long time to validate.
        """
        NUM_ADDRS = 100
        logging.info("testExcessiveSigops: Cleaning up node state")

        # We are not testing excessively sized blocks so make these large
        self.nodes[0].set("net.excessiveBlock=5000000")
        self.nodes[1].set("net.excessiveBlock=5000000")
        self.nodes[2].set("net.excessiveBlock=5000000")
        self.nodes[3].set("net.excessiveBlock=5000000")
        self.nodes[0].setminingmaxblock(5000000)
        self.nodes[1].setminingmaxblock(5000000)
        self.nodes[2].setminingmaxblock(5000000)
        self.nodes[3].setminingmaxblock(5000000)
        # Stagger the accept depths so we can see the block accepted stepwise
        self.nodes[0].set("net.excessiveAcceptDepth=0")
        self.nodes[1].set("net.excessiveAcceptDepth=1")
        self.nodes[2].set("net.excessiveAcceptDepth=2")
        self.nodes[3].set("net.excessiveAcceptDepth=3")

        for n in self.nodes:
            n.generate(10)
            self.sync_blocks()

        self.nodes[0].generate(100)  # create a lot of BTC for spending

        self.sync_all()

        self.nodes[0].set("net.excessiveSigopsPerMb=100")  # Set low so txns will fail if its used
        self.nodes[1].set("net.excessiveSigopsPerMb=5000")
        self.nodes[2].set("net.excessiveSigopsPerMb=1000")
        self.nodes[3].set("net.excessiveSigopsPerMb=100")

        logging.info("Creating addresses...")
        self.nodes[0].keypoolrefill(NUM_ADDRS)
        addrs = [self.nodes[0].getnewaddress() for _ in range(NUM_ADDRS)]

        # test that a < 1MB block ignores the sigops parameter
        self.nodes[0].setminingmaxblock(1000000)
        # if excessive Sigops was heeded, this txn would not make it into the block
        self.createUtxos(self.nodes[0], addrs, NUM_ADDRS)
        mpool = self.nodes[0].getmempoolinfo()
        assert_equal(mpool["size"], 0)

        # test that a < 1MB block ignores the sigops parameter, even if the max block size is less
        self.nodes[0].setminingmaxblock(5000000)
        # if excessive Sigops was heeded, this txn would not make it into the block
        self.createUtxos(self.nodes[0], addrs, NUM_ADDRS)
        mpool = self.nodes[0].getmempoolinfo()
        assert_equal(mpool["size"], 0)

        if self.extended:  # creating 1MB+ blocks is too slow for travis due to the signing cost
            self.createUtxos(self.nodes[0], addrs, 10000)  # we need a lot to generate 1MB+ blocks

            wallet = self.nodes[0].listunspent()
            wallet.sort(key=lambda x: x["amount"], reverse=True)
            self.nodes[0].set("net.excessiveSigopsPerMb=100000")  # Set this huge so all txns are accepted by this node

            logging.info("Generate > 1MB block with excessive sigops")
            self.generateTx(self.nodes[0], 1100000, addrs)

            counts = [x.getblockcount() for x in self.nodes]
            base = counts[0]

            self.nodes[0].generate(1)
            assert_equal(True, self.expectHeights([base + 1, base, base, base], 30))

            logging.info("Test excessive block propagation to nodes with different AD")
            self.nodes[0].generate(1)
            # it takes a while to sync all the txns
            assert_equal(True, self.expectHeights([base + 2, base + 2, base, base], 500))

            self.nodes[0].generate(1)
            assert_equal(True, self.expectHeights([base + 3, base + 3, base + 3, base], 90))

            self.nodes[0].generate(1)
            assert_equal(True, self.expectHeights([base + 4, base + 4, base + 4, base + 4], 90))

        logging.info("Excessive sigops test completed")

        # set it all back to defaults

        for n in self.nodes:
            n.generate(150)
            self.sync_blocks()

        self.nodes[0].set("net.excessiveSigopsPerMb=20000")  # Set low so txns will fail if its used
        self.nodes[1].set("net.excessiveSigopsPerMb=20000")
        self.nodes[2].set("net.excessiveSigopsPerMb=20000")
        self.nodes[3].set("net.excessiveSigopsPerMb=20000")

        self.nodes[0].setminingmaxblock(1000000)
        self.nodes[1].setminingmaxblock(1000000)
        self.nodes[2].setminingmaxblock(1000000)
        self.nodes[3].setminingmaxblock(1000000)
        self.nodes[0].set("net.excessiveBlock=1000000")
        self.nodes[1].set("net.excessiveBlock=1000000")
        self.nodes[2].set("net.excessiveBlock=1000000")
        self.nodes[3].set("net.excessiveBlock=1000000")

    def testExcessiveTx(self):
        """This test checks the behavior of the nodes in the presence of excessively large transactions.
           It will set the accept depth to different values on each node, and then verify that each node
           Does not follow the excessive tip until the accept depth is exceeded.

           The test also validates the rejection of a > 100kb transaction in a > 1MB block, and again
           watches as each node eventually accepts the large tx based on accept depth.
        """
        TEST_SIZE = 20
        logging.info("Test excessive transactions")
        if 1:
            tips = self.nodes[0].getchaintips()

            self.nodes[0].set("net.excessiveAcceptDepth=0")
            self.nodes[1].set("net.excessiveAcceptDepth=1")
            self.nodes[2].set("net.excessiveAcceptDepth=2")
            self.nodes[3].set("net.excessiveAcceptDepth=3")

            self.nodes[0].set("net.excessiveBlock=2000000")
            self.nodes[1].set("net.excessiveBlock=2000000")
            self.nodes[2].set("net.excessiveBlock=2000000")
            self.nodes[3].set("net.excessiveBlock=2000000")

            logging.info("Cleaning up node state")
            for n in self.nodes:
                n.generate(10)
                self.sync_blocks()

            self.sync_all()
            # verify mempool is cleaned up on all nodes
            mbefore = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
            assert_equal(mbefore, [(0, 0)] * 4)

            if 1:
                logging.info("Creating addresses...")
                self.nodes[0].keypoolrefill(TEST_SIZE + 1)
                addrs = [self.nodes[0].getnewaddress() for _ in range(TEST_SIZE + 1)]
            else:  # enable if you are using a pre-created wallet, as described above
                logging.info("Loading addresses...")
                with open("wallet10kAddrs.json") as f:
                    addrs = json.load(f)

            if 1:  # Test not relaying a large transaction

                # Make the excessive transaction size smaller so its quicker to produce a excessive one
                self.nodes[0].set("net.excessiveTx=100000")
                self.nodes[1].set("net.excessiveTx=100000")
                self.nodes[2].set("net.excessiveTx=100000")
                self.nodes[3].set("net.excessiveTx=100000")
                self.nodes[0].setminingmaxblock(1000000)
                self.nodes[1].setminingmaxblock(1000000)
                self.nodes[2].setminingmaxblock(1000000)
                self.nodes[3].setminingmaxblock(1000000)

                wallet = self.nodes[0].listunspent()
                wallet.sort(key=lambda x: x["amount"], reverse=True)
                while len(wallet) < 3000:
                    # Create a LOT of UTXOs
                    logging.info("Create lots of UTXOs...")
                    n = 0
                    group = min(100, TEST_SIZE)
                    count = 0
                    for w in wallet:
                        count += 1
                        split_transaction(self.nodes[0], [w], addrs[n:group + n])
                        n += group
                        if n >= len(addrs):
                            n = 0
                        if count > 50:  # We don't need any more
                            break
                    self.sync_all()
                    logging.info("mine blocks")
                    self.nodes[0].generate(5)  # mine all the created transactions
                    logging.info("sync all blocks and mempools")
                    self.sync_all()

                    wallet = self.nodes[0].listunspent()
                    wallet.sort(key=lambda x: x["amount"], reverse=True)

                logging.info("clean out the mempool")
                mbefore = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                while mbefore != [(0, 0)] * 4:
                    time.sleep(1)
                    self.nodes[0].generate(1)
                    time.sleep(10)
                    mbefore = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]

                # we need the mempool to be empty to track that this one tx doesn't prop
                assert_equal(mbefore, [(0, 0)] * 4)

                logging.info("Test not relaying a large transaction")

                (tx, vin, vout, txid) = split_transaction(self.nodes[0], wallet[0:3000], [addrs[0]], txfeePer=60)
                logging.debug("Transaction Length is: ", len(binascii.unhexlify(tx)))
                assert(len(binascii.unhexlify(tx)) > 100000)  # txn has to be big for the test to work

                mbefore = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                assert_equal(mbefore[1:], [(0, 0), (0, 0), (0, 0)])  # verify that the transaction did not propagate
                assert(mbefore[0][0] > 0)  # verify that the transaction is in my node

                logging.info("allowing tx a chance to propagate - sleeping...")
                while len(self.nodes[0].getmempoolinfo()) < 1:
                    logging.info("sleeping 1")
                    time.sleep(1)
                time.sleep(5)

                logging.info("Test a large transaction in block < 1MB")
                largeBlock = self.nodes[0].generate(1)
                self.sync_blocks()
                counts = [x.getblockcount() for x in self.nodes]
                latest = counts[0]
                # Verify that all nodes accepted the block, even if some of them didn't
                # have the transaction.  They should all accept a <= 1MB block with a tx
                # <= 1MB
                assert_equal(counts, [latest, latest, latest, latest])

            # this test checks the behavior of > 1MB blocks with excessive
            # transactions.  it takes a LONG time to generate and propagate 1MB+ txs.
            if self.extended:

                logging.info("Creating addresses...")
                self.nodes[0].keypoolrefill(2000)
                addrs = [self.nodes[0].getnewaddress() for _ in range(2000)]
                # Create a LOT of UTXOs for the next test
                wallet = self.nodes[0].listunspent()
                wallet.sort(key=lambda x: x["amount"], reverse=True)
                wlen = len(wallet)
                while wlen < 8000:
                    logging.info("Create lots of UTXOs by 100...")
                    n = 0
                    for w in wallet:
                        split_transaction(self.nodes[0], [w], addrs[n:100 + n])
                        logging.info(str(wlen))
                        n += 100
                        if n >= len(addrs):
                            n = 0
                        wlen += 99
                        if wlen > 8000:
                            break

                    blk = self.nodes[0].generate(1)
                    blkinfo = self.nodes[0].getblock(blk[0])
                    logging.info("Generated block %d size: %d, num tx: %d" %
                                 (blkinfo["height"], blkinfo["size"], len(blkinfo["tx"])))
                    wallet = self.nodes[0].listunspent()
                    wallet.sort(key=lambda x: x["amount"], reverse=True)
                    wlen = len(wallet)

                self.nodes[0].generate(1)
                self.sync_all()

                logging.info("Building > 1MB block...")
                # Set the excessive transaction size larger for this node so we can
                # generate an "excessive" block for the other nodes
                self.nodes[0].set("net.excessiveTx=1000000")

                self.generateTx(self.nodes[0], 1000000, addrs)

                # Now generate a > 100kb transaction & mine it into a > 1MB block

                self.nodes[0].setminingmaxblock(2000000)
                self.nodes[0].set("net.excessiveBlock=2000000")

                wallet.sort(key=lambda x: x["amount"], reverse=True)
                (tx, vin, vout, txid) = split_transaction(self.nodes[0], wallet[0:2500], [addrs[0]], txfeePer=60)
                logging.debug("Transaction Length is: ", len(binascii.unhexlify(tx)))
                assert(len(binascii.unhexlify(tx)) > 100000)  # txn has to be big for the test to work

                origCounts = [x.getblockcount() for x in self.nodes]
                base = origCounts[0]
                mpool = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                logging.debug(str(mpool))
                largeBlock = self.nodes[0].generate(1)
                mpool = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                logging.debug(str(mpool))

                logging.info("Syncing node1")
                largeBlock2 = self.nodes[0].generate(1)
                sync_blocks(self.nodes[0:2])
                mpool = [(lambda y: (y["size"], y["bytes"]))(x.getmempoolinfo()) for x in self.nodes]
                logging.debug(str(mpool))
                self.expectHeights([base + 2, base + 2, base, base], 30)

                logging.info("Syncing node2")
                largeBlock3 = self.nodes[0].generate(1)
                sync_blocks(self.nodes[0:3])
                self.expectHeights([base + 3, base + 3, base + 3, base], 30)

                logging.info("Syncing node3")
                largeBlock4 = self.nodes[0].generate(1)
                sync_blocks(self.nodes)
                self.expectHeights([base + 4, base + 4, base + 4, base + 4], 30)

            # Put it back to the default
            self.nodes[0].set("net.excessiveTx=1000000")
            self.nodes[1].set("net.excessiveTx=1000000")
            self.nodes[2].set("net.excessiveTx=1000000")
            self.nodes[3].set("net.excessiveTx=1000000")

    def repeatTx(self, count, node, addr, amt=1.0):
        for i in range(0, count):
            node.sendtoaddress(addr, amt)

    def generateAndPrintBlock(self, node):
        hsh = node.generate(1)
        inf = node.getblock(hsh[0])
        logging.info("block %d size %d" % (inf["height"], inf["size"]))
        return hsh

    def testExcessiveBlockSize(self):

        # get spendable coins
        if 0:
            for n in self.nodes:
                n.generate(1)
                self.sync_all()
            self.nodes[0].generate(100)

        self.sync_all()

        # Set the accept depth at 1, 2, and 3 and watch each nodes resist the chain for that long
        self.nodes[0].setminingmaxblock(5000)  # keep the generated blocks within 16*the EB so no disconnects
        self.nodes[1].setminingmaxblock(1000)
        self.nodes[2].setminingmaxblock(1000)
        self.nodes[3].setminingmaxblock(1000)

        self.nodes[1].setexcessiveblock(1000, 1)
        self.nodes[2].setexcessiveblock(1000, 2)
        self.nodes[3].setexcessiveblock(1000, 3)

        logging.info("Test excessively sized block, not propagating until accept depth is exceeded")
        addr = self.nodes[3].getnewaddress()
        # By using a very small value, it is likely that a single input is used.  This is important because
        # our mined block size is so small in this test that if multiple inputs are used the transactions
        # might not fit in the block.  This will give us a short block when the test expects a larger one.
        # To catch any of these short-block test malfunctions, the block size is printed out.
        self.repeatTx(8, self.nodes[0], addr, .001)
        counts = [x.getblockcount() for x in self.nodes]
        base = counts[0]
        logging.info("Starting counts: %s" % str(counts))
        logging.info("node0")
        self.generateAndPrintBlock(self.nodes[0])
        time.sleep(2)  # give blocks a chance to fully propagate
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 1, base, base, base])

        logging.info("node1")
        self.nodes[0].generate(1)
        sync_blocks(self.nodes[0:2])
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 2, base + 2, base, base])

        logging.info("node2")
        self.nodes[0].generate(1)
        sync_blocks(self.nodes[0:3])
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 3, base + 3, base + 3, base])

        logging.info("node3")
        self.nodes[0].generate(1)
        self.sync_all()
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 4] * 4)

        # Now generate another excessive block, but all nodes should snap right to
        # it because they have an older excessive block
        logging.info("Test immediate propagation of additional excessively sized block, due to prior excessive")
        self.repeatTx(8, self.nodes[0], addr, .001)
        self.nodes[0].generate(1)
        self.sync_all()
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 5] * 4)

        logging.info("Test daily excessive reset")
        # Now generate a day's worth of small blocks which should re-enable the
        # node's reluctance to accept a large block
        self.nodes[0].generate(6 * 24)
        sync_blocks(self.nodes)
        self.nodes[0].generate(5)  # plus the accept depths
        sync_blocks(self.nodes)
        self.repeatTx(8, self.nodes[0], addr, .001)
        base = self.nodes[0].getblockcount()
        print("base: %d" % base)
        self.generateAndPrintBlock(self.nodes[0])
        time.sleep(2)  # give blocks a chance to fully propagate
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 1, base, base, base])

        self.repeatTx(8, self.nodes[0], addr, .001)
        self.generateAndPrintBlock(self.nodes[0])
        time.sleep(2)  # give blocks a chance to fully propagate
        sync_blocks(self.nodes[0:2])
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 2, base + 2, base, base])

        self.repeatTx(5, self.nodes[0], addr, .001)
        self.generateAndPrintBlock(self.nodes[0])
        time.sleep(2)  # give blocks a chance to fully propagate
        sync_blocks(self.nodes[0:3])
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 3, base + 3, base + 3, base])

        self.repeatTx(5, self.nodes[0], addr, .001)
        self.generateAndPrintBlock(self.nodes[0])
        sync_blocks(self.nodes)
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 4] * 4)

        self.repeatTx(5, self.nodes[0], addr, .001)
        self.generateAndPrintBlock(self.nodes[0])
        sync_blocks(self.nodes)
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 5] * 4)

        logging.info("Test daily excessive reset #2")
        # Now generate a day's worth of small blocks which should re-enable the
        # node's reluctance to accept a large block + 10 because we have to get
        # beyond all the node's accept depths
        self.nodes[0].generate(6 * 24 + 10)
        sync_blocks(self.nodes)

        # counts = [ x.getblockcount() for x in self.nodes ]
        self.nodes[1].setexcessiveblock(100000, 1)  # not sure how big the txns will be but smaller than this
        self.nodes[1].setminingmaxblock(100000)  # not sure how big the txns will be but smaller than this
        self.repeatTx(20, self.nodes[0], addr, .001)
        base = self.nodes[0].getblockcount()
        self.generateAndPrintBlock(self.nodes[0])
        time.sleep(2)  # give blocks a chance to fully propagate
        sync_blocks(self.nodes[0:2])
        counts = [x.getblockcount() for x in self.nodes]
        assert_equal(counts, [base + 1, base + 1, base, base])

        logging.info("Random test")
        if self.extended:
            randomRange = 3
        else:
            randomRange = 2

        for i in range(0, randomRange):
            logging.info("round %d" % i)
            for n in self.nodes:
                size = random.randint(1, 1000) * 1000
                try:  # since miningmaxblock must be <= excessiveblock, raising/lowering may need to run these in different order
                    n.setminingmaxblock(size)
                    n.setexcessiveblock(size, random.randint(0, 10))
                except JSONRPCException:
                    n.setexcessiveblock(size, random.randint(0, 10))
                    n.setminingmaxblock(size)

            addrs = [x.getnewaddress() for x in self.nodes]
            ntxs = 0
            for i in range(0, random.randint(1, 200)):
                try:
                    self.nodes[random.randint(0, 3)].sendtoaddress(addrs[random.randint(0, 3)], .1)
                    ntxs += 1
                except JSONRPCException:  # could be spent all the txouts
                    pass
            logging.info("%d transactions" % ntxs)
            time.sleep(1)  # allow txns a chance to propagate
            self.nodes[random.randint(0, 3)].generate(1)
            logging.info("mined a block")
            # TODO:  rather than sleeping we should really be putting a check in here
            #       based on what the random excessive seletions were from above
            time.sleep(5)  # allow block a chance to propagate

        # the random test can cause disconnects if the block size is very large compared to excessive size
        # so reconnect
        interconnect_nodes(self.nodes)

if __name__ == '__main__':

    if "--extensive" in sys.argv:
        longTest = True
        # we must remove duplicate 'extensive' arg here
        while True:
            try:
                sys.argv.remove('--extensive')
            except:
                break
        logging.info("Running extensive tests")
    else:
        longTest = False

    ExcessiveBlockTest(longTest).main()

def info(type, value, tb):
    if hasattr(sys, 'ps1') or not sys.stderr.isatty():
        # we are in interactive mode or we don't have a tty-like
        # device, so we call the default hook
        sys.__excepthook__(type, value, tb)
    else:
        import traceback
        import pdb
        # we are NOT in interactive mode, print the exception...
        traceback.print_exception(type, value, tb)
        print
        # ...then start the debugger in post-mortem mode.
        pdb.pm()

sys.excepthook = info

def Test():
    t = ExcessiveBlockTest(True)
    bitcoinConf = {
        "debug": ["net", "blk", "thin", "mempool", "req", "bench", "evict"],  # "lck"
        "blockprioritysize": 2000000  # we don't want any transactions rejected due to insufficient fees...
    }
    t.main(["--tmpdir=/ramdisk/test", "--nocleanup", "--noshutdown"], bitcoinConf, None)


text:
package org.apache.river.test.impl.mahalo;

import java.util.logging.Level;

// Test harness specific classes
import java.io.IOException;

import org.apache.river.qa.harness.TestException;

import java.rmi.RemoteException;
import java.util.List;
import java.util.Arrays;

import org.apache.river.admin.DestroyAdmin;
import org.apache.river.admin.StorageLocationAdmin;

import net.jini.admin.Administrable;
import net.jini.admin.JoinAdmin;
import net.jini.core.entry.Entry;
import net.jini.core.discovery.LookupLocator;
import net.jini.discovery.LookupDiscovery;
import net.jini.event.EventMailbox;
import net.jini.lookup.entry.Name;

public abstract class AdminIFBase extends TxnMgrTestBase {

    protected boolean assertLocators(LookupLocator[] got, LookupLocator[] want)
    {

	if (got == null || want == null) { // check for null
	    return got == want;
	} else if (want.length == 0) {  // check for empty
	    return (got.length == 0);
	} else {
	    java.util.List gotList = java.util.Arrays.asList(got);
	    java.util.List wantList = java.util.Arrays.asList(want);
	    return gotList.containsAll(wantList);
	}
    }

    protected boolean assertLookupGroups(String[] got, String[] want) {

        if (got == null || want == null) {
            return got == want;
	} else if (want.length == 0) {
	    return got.length == 0;
	} else {
	    java.util.List gotList = java.util.Arrays.asList(got);
	    java.util.List wantList = java.util.Arrays.asList(want);
	    return gotList.containsAll(wantList);
	}
    }

    protected void dumpGroups(String[] got) {
        if (got == null)
	    logger.log(Level.INFO, "\t<ALL_GROUPS>");
	else if (got.length == 0)
	    logger.log(Level.INFO, "\t<NO_GROUPS>");
	else
	    for (int i = 0; i < got.length; i++) {
	        logger.log(Level.INFO, "\t" + got[i]);
	    }
    }

    protected boolean assertContainsName(Entry[] entries, String name) {
	for (int i = 0; i < entries.length; i++) {
	    if (entries[i] instanceof Name) {
		if(name.equals(((Name)entries[i]).name)) {
		    return true;
		}
	    }
	}
        return false;
    }

    protected void waitOnInput() {
        logger.log(Level.INFO, "Hit return to continue test");
        try {
            System.in.read();
        } catch (IOException e) {
            logger.log(Level.INFO,
		       "IOException while reading before exit " + e);
        }
    }

}


text:
package com.navercorp.pinpoint.web.vo.callstacks;

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

import com.navercorp.pinpoint.common.server.bo.AnnotationBo;
import com.navercorp.pinpoint.common.server.bo.ApiMetaDataBo;
import com.navercorp.pinpoint.common.service.AnnotationKeyRegistryService;
import com.navercorp.pinpoint.common.service.ServiceTypeRegistryService;
import com.navercorp.pinpoint.common.trace.AnnotationKey;
import com.navercorp.pinpoint.common.server.util.AnnotationUtils;
import com.navercorp.pinpoint.common.util.ApiDescription;
import com.navercorp.pinpoint.common.server.util.ApiDescriptionParser;
import com.navercorp.pinpoint.web.calltree.span.CallTreeNode;
import com.navercorp.pinpoint.web.calltree.span.SpanAlign;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

public class RecordFactory {
    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    // spans with id = 0 are regarded as root - start at 1
    private int idGen = 1;
    private ServiceTypeRegistryService registry;
    private AnnotationKeyRegistryService annotationKeyRegistryService;
    private final ApiDescriptionParser apiDescriptionParser = new ApiDescriptionParser();

    public RecordFactory(ServiceTypeRegistryService registry, AnnotationKeyRegistryService annotationKeyRegistryService) {
        this.registry = registry;
        this.annotationKeyRegistryService = annotationKeyRegistryService;
    }

    public Record get(final CallTreeNode node, final String argument) {
        final SpanAlign align = node.getValue();
        align.setId(getNextId());

        final int parentId = getParentId(node);
        Api api = getApi(align);

        final Record record = new Record(align.getDepth(),
                align.getId(),
                parentId,
                true,
                api.title,
                argument,
                align.getStartTime(),
                align.getElapsed(),
                align.getGap(),
                align.getAgentId(),
                align.getApplicationId(),
                registry.findServiceType(align.getServiceType()),
                align.getDestinationId(),
                align.isHasChild(),
                false,
                align.getTransactionId(),
                align.getSpanId(),
                align.getExecutionMilliseconds(),
                api.type);
        record.setSimpleClassName(api.className);
        record.setFullApiDescription(api.description);

        return record;
    }

    public Record getException(final int depth, final int parentId, final SpanAlign align) {
        if(!align.hasException()) {
            return null;
        }

        final Record record =  new Record(depth,
                getNextId(),
                parentId,
                false,
                getSimpleExceptionName(align.getExceptionClass()),
                align.getExceptionMessage(),
                0L, 0L, 0, null, null, null, null, false, true,
                align.getTransactionId(),
                align.getSpanId(),
                align.getExecutionMilliseconds(),
                0);

        return record;
    }

    private String getSimpleExceptionName(String exceptionClass) {
        if (exceptionClass == null) {
            return "";
        }
        final int index = exceptionClass.lastIndexOf('.');
        if (index != -1) {
            exceptionClass = exceptionClass.substring(index + 1, exceptionClass.length());
        }
        return exceptionClass;
    }

    public List<Record> getAnnotations(final int depth, final int parentId, SpanAlign align) {
        List<Record> list = new ArrayList<>();
        for(AnnotationBo annotation : align.getAnnotationBoList()) {
            final AnnotationKey key = findAnnotationKey(annotation.getKey());
            if (key.isViewInRecordSet()) {
                final Record record = new Record(depth,
                        getNextId(),
                        parentId,
                        false,
                        key.getName(),
                        annotation.getValue().toString(),
                        0L, 0L, 0, null, null, null, null, false, false, null, 0, 0, 0);
                list.add(record);
            }
        }

        return list;
    }

    public Record getParameter(final int depth, final int parentId, final String method, final String argument) {
        return new Record(depth,
                getNextId(),
                parentId,
                false,
                method,
                argument,
                0L, 0L, 0, null, null, null, null, false, false, null, 0, 0, 0);
    }

    int getParentId(final CallTreeNode node) {
        final CallTreeNode parent = node.getParent();
        if (parent == null) {
            if(!node.getValue().isSpan()) {
                throw new IllegalStateException("parent is null. node=" + node);
            }

            return 0;
        }

        return parent.getValue().getId();
    }

    Api getApi(final SpanAlign align) {
        final Api api = new Api();

        final AnnotationBo annotation =  AnnotationUtils.findAnnotationBo(align.getAnnotationBoList(), AnnotationKey.API_METADATA);

        if (annotation != null) {
            final ApiMetaDataBo apiMetaData = (ApiMetaDataBo) annotation.getValue();
            api.title = api.description = getApiInfo(apiMetaData);
            if (apiMetaData.getType() == 0) {
                try {
                    ApiDescription apiDescription = apiDescriptionParser.parse(api.description);
                    api.title = apiDescription.getSimpleMethodDescription();
                    api.className = apiDescription.getSimpleClassName();
                } catch(Exception e) {
                    logger.warn("Failed to api parse. {}", api.description, e);
                }
            }
            api.type = apiMetaData.getType();
        } else {
            AnnotationKey apiMetaDataError = getApiMetaDataError(align.getAnnotationBoList());
            api.title = apiMetaDataError.getName();
        }

        return api;
    }

    private String getApiInfo(ApiMetaDataBo apiMetaDataBo) {
        if (apiMetaDataBo.getLineNumber() != -1) {
            return apiMetaDataBo.getApiInfo() + ":" + apiMetaDataBo.getLineNumber();
        } else {
            return apiMetaDataBo.getApiInfo();
        }
    }

    public AnnotationKey getApiMetaDataError(List<AnnotationBo> annotationBoList) {
        for (AnnotationBo bo : annotationBoList) {
            AnnotationKey apiErrorCode = annotationKeyRegistryService.findApiErrorCode(bo.getKey());
            if (apiErrorCode != null) {
                return apiErrorCode;
            }
        }
        // could not find a more specific error - returns generalized error
        return AnnotationKey.ERROR_API_METADATA_ERROR;
    }

    private AnnotationKey findAnnotationKey(int key) {
        return annotationKeyRegistryService.findAnnotationKey(key);
    }

    private int getNextId() {
        return idGen++;
    }

    private static class Api {
        private String title = "";
        private String className = "";
        private String description = "";
        private int type = 0;
    }
}


text:
<!DOCTYPE html>

  <title>window-onerror</title>


text:
FCKLang.PlaceholderBtn			= 'Insert/Edit Placeholder' ;
FCKLang.PlaceholderDlgTitle		= 'Placeholder Properties' ;
FCKLang.PlaceholderDlgName		= 'Placeholder Name' ;
FCKLang.PlaceholderErrNoName	= 'Please type the placeholder name' ;
FCKLang.PlaceholderErrNameInUse	= 'The specified name is already in use' ;