text:
class CocoaPod
  include Persistence
  include ::ActiveModel::Model
  include ::ActiveModel::Serialization

  validates_presence_of :name

  attr_accessor :name,
                :category_name,
                :updated_at,
                :stars,
                :pushed_at,
                :website_url,
                :source_url,
                :doc_url,
                :version,
                :summary,
                :dependencies,
                :dependents

  def cocoa_pod_category
    CocoaPodCategory.find(category_name)
  end

  def stars
    @stars || 0
  end

  def dependents
    @dependents || []
  end

  def dependencies
    @dependencies || []
  end

  def category_name
    @category_name || 'uncategorized'
  end

  def updated_at
    @updated_at || Time.now - 1.year
  end

  def serializable_hash context=nil
    {
      'name' => name,
      'stars' => stars,
      'pushed_at' => pushed_at.to_s,
      'website_url' => website_url,
      'source_url' => source_url,
      'doc_url' => doc_url,
      'version' => version,
      'summary' => summary || "",
      'category_name' => category_name,
      'dependencies' => dependencies,
      'dependents' => dependents
    }
  end

  def self.collection_name
    :pods
  end

  def self.delete_all_dependencies
    h = DB[collection_name] || {}
    h.each do |k,v|
      v['dependencies'] = []
      v['dependents'] = []
    end
    DB[collection_name] ||= {}
  end
end


text:
;(function(_, _defineProperty, _keys, _freeze, _nullptr) {
/**
 * new static_iterator(o, _keys(o));
 * Allows the iteration across enumerable properties of objects.
 * Though the byte size does grow as the number of enumerable properties increases
 * can move quickly through the properties. Also, if any new properties are added or
 * removed from the scope, the iterator will not know.
 *
 * @param scope : The object for the iterator to move through.
 * @param props : An array of enumerable property names for the scope.
 */
function static_iterator(scope, props) {
	var // Scope for the iterator to run through.
		_scope = scope,
		// The properties that are enumerable of the scope.
		_props = props,
		// The instance being created.
		me 	   = this,
		// The current property the iterator is on.
		_i	   = 0,
		// The amount of properties there are.
		_l	   = props.length;
	// Used to convert the iterator into its indexed value.
	_defineProperty(me, 'valueOf', {value:function(){return _i}});
	// Used to alow access to the current scope of the iterator.
	_defineProperty(me, 'scope', {get: function(){return _scope}});
	// Returns the current property the iterator is pointing or returns nullptr.
	_defineProperty(me, 'prop', {get:function(){return 0 <= _i && _i < _l ? _props[_i] : iter.nullptr}});
	// Property that returns itself. Will return nullptr if out of bounds.
	// Also can be used to set the current index if the new value is a number.
	_defineProperty(me, 'me', {
		get: function(){return 0 <= _i && _i < _l ? me : iter.nullptr},
		set: function(v){if(!isNaN(v = +v)) _i = v}
	});
	// Dereferences the iterator to get what it is pointing to.
	_defineProperty(me, '$', {
		get: function(){return _scope[_props[_i]]},
		set: function(v){_scope[_props[_i]] = v}
	});
	// Moves the iterator to the last property and returns itself.
	_defineProperty(me, 'last', {
		get: function() {
			_i = _l - 1;
			return me;
		}
	});
	// Moves the iterator to the first property and returns itself.
	_defineProperty(me, 'first', {
		get: function() {
			_i = 0;
			return me;
		}
	});
	// Moves the iterator up one then returns itself.
	_defineProperty(me, 'next', {
		get: function() {
			++_i;
			return me;
		}
	});
	// Moves the iterator down one then returns itself.
	_defineProperty(me, 'prev', {
		get: function() {
			--_i;
			return me;
		}
	});
};

/**
 * iter([Object])
 * The function that creates iterators based off of input.
 *
 * @param o : The object to create an iterator for. If not provided correctly will
 * 			  return nullptr.
 *
 * @return Returns a new static_iterator wrapped around the object.
 */
function iter(o) {
	// Makes sure that o is an actual object.
	if(o === undefined || o === null) return iter.nullptr;
	// Creates the iterator.
	return new static_iterator(o,_keys(o));
};

/**
 * Takes in an object and calcualtes the number of enumerable properties
 * it has. If the object is an iterator objet then it will calculate
 * the length of the iterator.
 *
 * @param i : The object whose length is to be calculated.
 *
 * @return Returns either the number of enumerable properties an
 *         object has or the length of an iterator.
 */
_defineProperty(iter, "length", {value: function length(i) {
	// If undefined, null, or nullptr then return zero.
	if(i === undefined || i === null || i === iter.nullptr)
		return 0;
	// Checks to see of it is a static_iterator.
	if(i instanceof static_iterator)
	{
		// Stores the current location of the iterator.
		var temp = +i,
		// Calculates the length of the iterator by going to the
		// last element then adding one to the index.
			size = +i.last + 1;
		// Resets the iterator.
		i.me = temp;
		// Defines the property length to the iterator.
		_defineProperty(i, "length", {value:size, configurable:true, writable:true});
		// Returns the size calculated.
		return size;
	}
	// If not an iterator then return the number of
	// enumerable properties the object passed in has.
	return _keys(i).length;
}});

// Object used as the nullptr for iterators.
_defineProperty(iter, 'nullptr', {value:
	// Makes sure there is a nullptr object.
	_nullptr ||
	_freeze(new (function nullptr(){
		_defineProperty(this, 'valueOf', {value:function(){return NaN}});
	}))
});

// The current version of iter.js.
_defineProperty(iter, 'VERSION', {value:'1.1.0'});

// Attaches to the space loaded into.
_defineProperty(_, 'iter', {value:iter,enumerable:true});
}).call(this, this, Object.defineProperty, Object.keys, Object.freeze, this.nullptr)

redpajama_set_name: RedPajamaGithub


text:
package de.wirecard.accept.sample;

import android.bluetooth.BluetoothAdapter;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.widget.Button;
import android.widget.TextView;

import de.wirecard.accept.extension.refactor.AcceptThyronPaymentFlowController;
import de.wirecard.accept.sdk.AcceptSDK;
import de.wirecard.accept.sdk.extensions.Device;
import de.wirecard.accept.sdk.extensions.PaymentFlowController;

/**
 * responsible for phisicaly communication with terminal during FW or Device config update
 * download files, store it and upload to Spire terminal
 *
 * Configuration update is just about start communication with terminal, because its automatic (can happend that it will be sterted during your first payment, if not connected yet)
 * Firmware update requires two steps. Firmware version check, and AcceptThyronPaymentFlowController.connectAndConfigure()... this is done here in this activity.
 */
public class ConfigurationAndFirmwareUpdateActivity extends BaseActivity implements PaymentFlowController.ConfigureListener {
    private static String TAG = ConfigurationAndFirmwareUpdateActivity.class.getSimpleName();

    public static final String EXTRA_SELECTED_DEVICE = "selected_device";
    public static final String EXTRA_ITS_FIRMWARE_UPDATE_ALOWED = "firmware_update_alowed_mode";

    TextView message_text;
    TextView progress_text;
    Button cancelButton;

    private Device currentDev;
    private AcceptThyronPaymentFlowController controller = null; //old version of implementation
    private boolean firmwareUpdateAlowedMode = true;
    private boolean finishedUpdate = false;

    public static Intent intent(final Context context) {
        return new Intent(context, ConfigurationAndFirmwareUpdateActivity.class);
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_firmware_update);
        configInProgressFileCounter = 0;
        message_text = (TextView) findViewById(R.id.textViewMessage);
        progress_text = (TextView) findViewById(R.id.textViewProgress);
        onConnectionStarted();

        cancelButton = (Button) findViewById(R.id.button);
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                //result is set
                finish();
            }
        });
        firmwareUpdateAlowedMode = getIntent().getExtras().getBoolean(ConfigurationAndFirmwareUpdateActivity.EXTRA_ITS_FIRMWARE_UPDATE_ALOWED, true);

        // create default controller using .. new AcceptThyronPaymentFlowController() in case you will not use usb,
        // because demo is parametrised here is used full constructor instead
        controller = new AcceptThyronPaymentFlowController(true, false, ((Application) getApplicationContext()).usb);
        currentDev = getIntent().getExtras().getParcelable(ConfigurationAndFirmwareUpdateActivity.EXTRA_SELECTED_DEVICE);
        setResult(RESULT_CANCELED);
    }

    @Override
    protected void onStart() {
        super.onStart();
        //demo app feature ... check if BT is on
        boolean usb = ((Application) getApplicationContext()).usb;
        if (!usb) {
            //check BT first.
            BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
            if (mBluetoothAdapter == null) {
                progress_text.setText("bluetooth_is_currently_powered_off");
                message_text.setText("Enable Bluetooth and try again");
                return;
            }
        }

        //connectAndConfigure is new, "whole firmware update process wrapping" method,
        // using async tasks for download fresh data from backend from remembered url in previous steps(>>> MenuActivity.showFirmwareAndConfigActivity())
        // !!! pls use with firmwareUpdateAllowed = true only if you will run firmware update.
        //public void connectAndConfigure(final Context context, final Device currentUsedDevice, final ConfigureListener configureListener, final boolean firmwareUpdateAllowed) {
        controller.connectAndConfigure(this, currentDev, ConfigurationAndFirmwareUpdateActivity.this, firmwareUpdateAlowedMode);

        // !!! if not needed firmware update use firmwareUpdateAllowed = false
    }

    @Override
    public void onConfigurationStarted() {
        onConnectionStarted();
        if (firmwareUpdateAlowedMode) {
            showFirmwareScreen_LoadingVersionInfo();
        }
    }

    private int configInProgressFileCounter = 0;

    @Override
    public void onConfigurationInProgress(PaymentFlowController.ConfigProgressState state, String message) {
        progress_text.setText("Processing...");
        switch (state) {
            case FW_UPDATE_IN_PROGRESS:
                // we have to display conditionally also firmware update message witch some params
                message_text.setText(getString(R.string.general_firmware_update_pending,
                        AcceptSDK.getTerminalInfo() != null ? AcceptSDK.getTerminalInfo().firmwareVersion : "-",
                        AcceptSDK.getCurrentVersionOfSavedFirmwareInBackend() != null ? AcceptSDK.getCurrentVersionOfSavedFirmwareInBackend().getFwNumber() : "-"));
                return;
            case CONFIGURATION_UPDATE_FILE_COUNTER:
                // because here can be received during FW update also currentUsedDevice config events(if currentUsedDevice not updated config yet)
                message_text.setText(state + " (File " + ++configInProgressFileCounter + ")");
                return;
            default:
                message_text.setText("Config update");
        }
    }

    @Override
    public void onConfigureSuccess(boolean restarted) {
        progress_text.setText(" ");
        if (firmwareUpdateAlowedMode) {
            message_text.setText("New firmware installed successfully");
        }
        else {
            message_text.setText("New configuration installed successfully");
            if(restarted){
                message_text.setText("New configuration installed successfully, \n please wait for restart");
            }
        }
        finishedUpdate = true;
        if (restarted)
            cancelButton.setText("Restart done");
        else
            cancelButton.setText("Done");

        setResult(RESULT_OK);
    }

    @Override
    public void onConfigureError(PaymentFlowController.Error error, String errorMessage) {
        if (!finishedUpdate)
            showFailScreen(error, errorMessage);
    }

    private void showFirmwareScreen_LoadingVersionInfo() {
        progress_text.setText("PROGRESS_STATE_CONTACTING");
        message_text.setText("Downloading firmware please wait");
    }

    private void showFailScreen(PaymentFlowController.Error error, String errorMessage) {
        progress_text.setText("=ERROR=");
        message_text.setText("Pairing: connect failed");
        if (error != null)
            progress_text.setText(error.name());

        if (!TextUtils.isEmpty(errorMessage))
            message_text.setText("Pairing: connect failed");
    }

    public void onConnectionStarted() {
        Log.d(TAG, "onConnectionStarted");
        progress_text.setText("CONNECTING");
        message_text.setText("Pairing: connecting");
    }

    @Override
    protected void onDestroy() {
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_KEEP_SCREEN_ON);
        controller = null;
        finish();
        super.onDestroy();
    }

    @Override
    public void onBackPressed() {
        setResult(RESULT_CANCELED);
        super.onBackPressed();
    }
}


text:
var from;

//// [fromAsIdentifier1.js]
var from;


text:
/*
 * MIT License
 */
package aw2079.todoapp.Services;

import aw2079.todoapp.Model.Repositories.UserDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 *
 * @author Artur Wiśniewski
 */
@Service
public class UserService {

    @Autowired
    UserDao dao;

    public String first(){
        return dao.first().toString();
        //return dao.findById(1L).toString();
    }

}


text:
import sys, os, shutil, gc
import string, re
from math import sqrt, log
from getopt import getopt

GC_REF_KIND = 0
VALID_REF_KIND = 1
RESOURCE_REF_KIND = 2
REMOTE_REF_KIND = 3

prefix = r'\[(?P<realmnode>[0-9]+) - (?P<thread>[0-9a-f]+)\] \{\w+\}\{legion_gc\}: '
# References
add_base_ref_pat = re.compile(prefix + r'GC Add Base Ref (?P<kind>[0-9]+) (?P<did>[0-9]+) (?P<node>[0-9]+) (?P<src>[0-9]+) (?P<cnt>[0-9]+)')
add_nested_ref_pat = re.compile(prefix + r'GC Add Nested Ref (?P<kind>[0-9]+) (?P<did>[0-9]+) (?P<node>[0-9]+) (?P<src>[0-9]+) (?P<cnt>[0-9]+)')
remove_base_ref_pat = re.compile(prefix + r'GC Remove Base Ref (?P<kind>[0-9]+) (?P<did>[0-9]+) (?P<node>[0-9]+) (?P<src>[0-9]+) (?P<cnt>[0-9]+)')
remove_nested_ref_pat = re.compile(prefix + r'GC Remove Nested Ref (?P<kind>[0-9]+) (?P<did>[0-9]+) (?P<node>[0-9]+) (?P<src>[0-9]+) (?P<cnt>[0-9]+)')
# Instances
inst_manager_pat = re.compile(prefix + r'GC Instance Manager (?P<did>[0-9]+) (?P<node>[0-9]+) (?P<iid>[a-f0-9]+) (?P<mem>[a-f0-9]+)')
list_manager_pat = re.compile(prefix + r'GC List Reduction Manager (?P<did>[0-9]+) (?P<node>[0-9]+) (?P<iid>[a-f0-9]+) (?P<mem>[a-f0-9]+)')
fold_manager_pat = re.compile(prefix + r'GC Fold Reduction Manager (?P<did>[0-9]+) (?P<node>[0-9]+) (?P<iid>[a-f0-9]+) (?P<mem>[a-f0-9]+)')
# Views
materialize_pat = re.compile(prefix + r'GC Materialized View (?P<did>[0-9]+) (?P<node>[0-9]+) (?P<inst>[0-9]+)')
composite_pat = re.compile(prefix + r'GC Composite View (?P<did>[0-9]+) (?P<node>[0-9]+)')
fill_pat = re.compile(prefix + r'GC Fill View (?P<did>[0-9]+) (?P<node>[0-9]+)')
reduction_pat = re.compile(prefix + r'GC Reduction View (?P<did>[0-9]+) (?P<node>[0-9]+) (?P<inst>[0-9]+)')
# Version State
version_state_pat = re.compile(prefix + r'GC Version State (?P<did>[0-9]+) (?P<node>[0-9]+)')
# Future
future_pat = re.compile(prefix + r'GC Future (?P<did>[0-9]+) (?P<node>[0-9]+)')
# Constraints
constraints_pat = re.compile(prefix + r'GC Constraints (?P<did>[0-9]+) (?P<node>[0-9]+)')
# Source Kinds
source_kind_pat = re.compile(prefix + r'GC Source Kind (?P<kind>[0-9]+) (?P<name>[0-9a-zA-Z_ ]+)')
# Deletion Pattern
deletion_pat = re.compile(prefix + r'GC Deletion (?P<did>[0-9]+) (?P<node>[0-9]+)')

class TracePrinter(object):
    def __init__(self):
        self.depth = 0

    def down(self):
        self.depth += 1

    def up(self):
        assert self.depth > 0
        self.depth -= 1

    def print_base(self, obj):
        self.println(repr(obj))

    def println(self, line):
        for idx in range(self.depth):
            line = '  '+line
        print line

class Base(object):
    def __init__(self, did, node):
        self.did = did
        self.node = node
        self.base_gc_refs = {}
        self.base_gc_adds = {}
        self.base_gc_rems = {}
        self.base_valid_refs = {}
        self.base_valid_adds = {}
        self.base_valid_rems = {}
        self.base_remote_refs = {}
        self.base_remote_adds = {}
        self.base_remote_rems = {}
        self.base_resource_refs = {}
        self.base_resource_adds = {}
        self.base_resource_rems = {}
        self.nested_gc_refs = {}
        self.nested_gc_adds = {}
        self.nested_gc_rems = {}
        self.nested_valid_refs = {}
        self.nested_valid_adds = {}
        self.nested_valid_rems = {}
        self.nested_remote_refs = {}
        self.nested_remote_adds = {}
        self.nested_remote_rems = {}
        self.nested_resource_refs = {}
        self.nested_resource_adds = {}
        self.nested_resource_rems = {}
        self.on_stack = False
        self.deleted = False
        self.checked = False

    def add_base_ref(self, kind, src, cnt):
        if kind is GC_REF_KIND:
            if src in self.base_gc_refs:
                self.base_gc_refs[src] += cnt
                self.base_gc_adds[src] += cnt
            else:
                self.base_gc_refs[src] = cnt
                self.base_gc_adds[src] = cnt
                self.base_gc_rems[src] = 0
        elif kind is VALID_REF_KIND:
            if src in self.base_valid_refs:
                self.base_valid_refs[src] += cnt
                self.base_valid_adds[src] += cnt
            else:
                self.base_valid_refs[src] = cnt
                self.base_valid_adds[src] = cnt
                self.base_valid_rems[src] = 0
        elif kind is REMOTE_REF_KIND:
            if src in self.base_remote_refs:
                self.base_remote_refs[src] += cnt
                self.base_remote_adds[src] += cnt
            else:
                self.base_remote_refs[src] = cnt
                self.base_remote_adds[src] = cnt
                self.base_remote_rems[src] = 0
        elif kind is RESOURCE_REF_KIND:
            if src in self.base_resource_refs:
                self.base_resource_refs[src] += cnt
                self.base_resource_adds[src] += cnt
            else:
                self.base_resource_refs[src] = cnt
                self.base_resource_adds[src] = cnt
                self.base_resource_rems[src] = 0
        else:
            print 'BAD BASE REF '+str(kind)
            assert False

    def add_nested_ref(self, kind, src, cnt):
        if kind is GC_REF_KIND:
            if src in self.nested_gc_refs:
                self.nested_gc_refs[src] += cnt
                self.nested_gc_adds[src] += cnt
            else:
                self.nested_gc_refs[src] = cnt
                self.nested_gc_adds[src] = cnt
                self.nested_gc_rems[src] = 0
        elif kind is VALID_REF_KIND:
            if src in self.nested_valid_refs:
                self.nested_valid_refs[src] += cnt
                self.nested_valid_adds[src] += cnt
            else:
                self.nested_valid_refs[src] = cnt
                self.nested_valid_adds[src] = cnt
                self.nested_valid_rems[src] = 0
        elif kind is REMOTE_REF_KIND:
            if src in self.nested_remote_refs:
                self.nested_remote_refs[src] += cnt
                self.nested_remote_adds[src] += cnt
            else:
                self.nested_remote_refs[src] = cnt
                self.nested_remote_adds[src] = cnt
                self.nested_remote_rems[src] = 0
        elif kind is RESOURCE_REF_KIND:
            if src in self.nested_resource_refs:
                self.nested_resource_refs[src] += cnt
                self.nested_resource_adds[src] += cnt
            else:
                self.nested_resource_refs[src] = cnt
                self.nested_resource_adds[src] = cnt
                self.nested_resource_rems[src] = 0
        else:
            assert False

    def remove_base_ref(self, kind, src, cnt):
        if kind is GC_REF_KIND:
            if src in self.base_gc_refs:
                self.base_gc_refs[src] -= cnt
                self.base_gc_rems[src] += cnt
            else:
                self.base_gc_refs[src] = -cnt
                self.base_gc_adds[src] = 0
                self.base_gc_rems[src] = cnt
        elif kind is VALID_REF_KIND:
            if src in self.base_valid_refs:
                self.base_valid_refs[src] -= cnt
                self.base_valid_rems[src] += cnt
            else:
                self.base_valid_refs[src] = -cnt
                self.base_valid_adds[src] = 0
                self.base_valid_rems[src] = cnt
        elif kind is REMOTE_REF_KIND:
            if src in self.base_remote_refs:
                self.base_remote_refs[src] -= cnt
                self.base_remote_rems[src] += cnt
            else:
                self.base_remote_refs[src] = -cnt
                self.base_remote_adds[src] = 0
                self.base_remote_rems[src] = cnt
        elif kind is RESOURCE_REF_KIND:
            if src in self.base_resource_refs:
                self.base_resource_refs[src] -= cnt
                self.base_resource_rems[src] += cnt
            else:
                self.base_resource_refs[src] = -cnt
                self.base_resource_adds[src] = 0
                self.base_resource_rems[src] = cnt
        else:
            assert False

    def remove_nested_ref(self, kind, src, cnt):
        if kind is GC_REF_KIND:
            if src in self.nested_gc_refs:
                self.nested_gc_refs[src] -= cnt
                self.nested_gc_rems[src] += cnt
            else:
                self.nested_gc_refs[src] = -cnt
                self.nested_gc_adds[src] = 0
                self.nested_gc_rems[src] = cnt
        elif kind is VALID_REF_KIND:
            if src in self.nested_valid_refs:
                self.nested_valid_refs[src] -= cnt
                self.nested_valid_rems[src] += cnt
            else:
                self.nested_valid_refs[src] = -cnt
                self.nested_valid_adds[src] = 0
                self.nested_valid_rems[src] = cnt
        elif kind is REMOTE_REF_KIND:
            if src in self.nested_remote_refs:
                self.nested_remote_refs[src] -= cnt
                self.nested_remote_rems[src] += cnt
            else:
                self.nested_remote_refs[src] = -cnt
                self.nested_remote_adds[src] = 0
                self.nested_remote_rems[src] = cnt
        elif kind is RESOURCE_REF_KIND:
            if src in self.nested_resource_refs:
                self.nested_resource_refs[src] -= cnt
                self.nested_resource_rems[src] += cnt
            else:
                self.nested_resource_refs[src] = -cnt
                self.nested_resource_adds[src] = 0
                self.nested_resource_rems[src] = cnt
        else:
            assert False

    def clone(self, other):
        assert self.did == other.did
        self.base_gc_refs = other.base_gc_refs
        self.base_gc_adds = other.base_gc_adds
        self.base_gc_rems = other.base_gc_rems
        self.base_valid_refs = other.base_valid_refs
        self.base_valid_adds = other.base_valid_adds
        self.base_valid_rems = other.base_valid_rems
        self.base_remote_refs = other.base_remote_refs
        self.base_remote_adds = other.base_remote_adds
        self.base_remote_rems = other.base_remote_rems
        self.base_resource_refs = other.base_resource_refs
        self.base_resource_adds = other.base_resource_adds
        self.base_resource_rems = other.base_resource_rems
        self.nested_gc_refs = other.nested_gc_refs
        self.nested_gc_adds = other.nested_gc_adds
        self.nested_gc_rems = other.nested_gc_rems
        self.nested_valid_refs = other.nested_valid_refs
        self.nested_valid_adds = other.nested_valid_adds
        self.nested_valid_rems = other.nested_valid_rems
        self.nested_remote_refs = other.nested_remote_refs
        self.nested_remote_adds = other.nested_remote_adds
        self.nested_remote_rems = other.nested_remote_rems
        self.nested_resource_refs = other.nested_resource_refs
        self.nested_resource_adds = other.nested_resource_adds
        self.nested_resource_rems = other.nested_resource_rems
        self.deleted = other.deleted

    def update_nested_references(self, state):
        if self.nested_gc_refs:
            new_gc_refs = dict()
            new_gc_adds = dict()
            new_gc_rems = dict()
            for did,refs in self.nested_gc_refs.iteritems():
                src = state.get_obj(did, self.node)
                new_gc_refs[src] = refs
                new_gc_adds[src] = self.nested_gc_adds[did]
                new_gc_rems[src] = self.nested_gc_rems[did]
            self.nested_gc_refs = new_gc_refs
            self.nested_gc_adds = new_gc_adds
            self.nested_gc_rems = new_gc_rems
        if self.nested_valid_refs:
            new_valid_refs = dict()
            new_valid_adds = dict()
            new_valid_rems = dict()
            for did,refs in self.nested_valid_refs.iteritems():
                src = state.get_obj(did, self.node)
                new_valid_refs[src] = refs
                new_valid_adds[src] = self.nested_valid_adds[did]
                new_valid_rems[src] = self.nested_valid_rems[did]
            self.nested_valid_refs = new_valid_refs
            self.nested_valid_adds = new_valid_adds
            self.nested_valid_rems = new_valid_rems
        if self.nested_remote_refs:
            new_remote_refs = dict()
            new_remote_adds = dict()
            new_remote_rems = dict()
            for did,refs in self.nested_remote_refs.iteritems():
                src = state.get_obj(did, self.node)
                new_remote_refs[src] = refs
                new_remote_adds[src] = self.nested_remote_adds[did]
                new_remote_rems[src] = self.nested_remote_rems[did]
            self.nested_remote_refs = new_remote_refs
            self.nested_remote_adds = new_remote_adds
            self.nested_remote_rems = new_remote_rems
        if self.nested_resource_refs:
            new_resource_refs = dict()
            new_resource_adds = dict()
            new_resource_rems = dict()
            for did,refs in self.nested_resource_refs.iteritems():
                src = state.get_obj(did, self.node)
                new_resource_refs[src] = refs
                new_resource_adds[src] = self.nested_resource_adds[did]
                new_resource_rems[src] = self.nested_resource_rems[did]
            self.nested_resource_refs = new_resource_refs
            self.nested_resource_adds = new_resource_adds
            self.nested_resource_rems = new_resource_rems

    def check_for_leaks(self, verbose):
        if self.deleted:
            if verbose:
                print "----------------------------------------------------------------"
                print str(self)+' was properly deleted'
                printer = TracePrinter()
                self.report_references(printer, GC_REF_KIND, verbose)
                self.report_references(printer, VALID_REF_KIND, verbose)
                self.report_references(printer, REMOTE_REF_KIND, verbose)
                self.report_references(printer, RESOURCE_REF_KIND, verbose)
                print "----------------------------------------------------------------"
            else:
                print str(self)+' was properly deleted'
            if isinstance(self,Manager):
                return (True,False)
            return True
        # Special case if this is an instance that the user pinned
        # then we don't need to report this as an error
        if isinstance(self,Manager):
            is_pinned = False
            for kind in self.base_valid_refs.iterkeys():
                if kind == 'Never GC Reference':
                    is_pinned = True
                    break
            if is_pinned:
                if verbose:
                    print "----------------------------------------------------------------"
                    print "INFO: "+str(self)+' was not deleted because it was pinned by the user'
                    printer = TracePrinter()
                    self.report_references(printer, GC_REF_KIND, verbose)
                    self.report_references(printer, VALID_REF_KIND, verbose)
                    self.report_references(printer, REMOTE_REF_KIND, verbose)
                    self.report_references(printer, RESOURCE_REF_KIND, verbose)
                    print "----------------------------------------------------------------"
                else:
                    print "INFO: "+str(self)+' was not deleted because it was pinned by the user'
                return (False,True)
        print "----------------------------------------------------------------"
        print "ERROR: "+str(self)+" was not properly deleted"
        printer = TracePrinter()
        self.report_references(printer, GC_REF_KIND, verbose)
        self.report_references(printer, VALID_REF_KIND, verbose)
        self.report_references(printer, REMOTE_REF_KIND, verbose)
        self.report_references(printer, RESOURCE_REF_KIND, verbose)
        print "----------------------------------------------------------------"
        if isinstance(self,Manager):
            return (False,False)
        return False

    def report_references(self, printer, kind, verbose):
        printer.down()
        if kind == GC_REF_KIND and self.base_gc_refs:
            for kind,refs in self.base_gc_refs.iteritems():
                if refs == 0:
                    if verbose:
                        printer.println('Empty (Refs=0): Base GC '+kind+
                            ' (Adds='+str(self.base_gc_adds[kind])+',Rems='+str(self.base_gc_rems[kind])+')')
                else:
                    if verbose:
                        printer.println('NON-EMPTY (Refs='+str(refs)+'): Base GC '+kind+
                            ' (Adds='+str(self.base_gc_adds[kind])+',Rems='+str(self.base_gc_rems[kind])+')')
                    else:
                        printer.println('Base GC '+kind+' (Refs='+str(refs)+')')
        if kind == VALID_REF_KIND and self.base_valid_refs:
            for kind,refs in self.base_valid_refs.iteritems():
                if refs == 0:
                    if verbose:
                        printer.println('Empty (Refs=0): Base Valid '+kind+
                            ' (Adds='+str(self.base_valid_adds[kind])+',Rems='+str(self.base_valid_rems[kind])+')')
                else:
                    if verbose:
                        printer.println('NON-EMPTY (Refs='+str(refs)+'): Base Valid '+kind+
                            ' (Adds='+str(self.base_valid_adds[kind])+',Rems='+str(self.base_valid_rems[kind])+')')
                    else:
                        printer.println('Base Valid '+kind+' (Refs='+str(refs)+')')
        if kind == REMOTE_REF_KIND and self.base_remote_refs:
            for kind,refs in self.base_remote_refs.iteritems():
                if refs == 0:
                    if verbose:
                        printer.println('Empty (Refs=0): Base Remote '+kind+
                            ' (Adds='+str(self.base_remote_adds[kind])+',Rems='+str(self.base_remote_rems[kind])+')')
                else:
                    if verbose:
                        printer.println('NON-EMPTY (Refs='+str(refs)+'): Base Remote '+kind+
                            ' (Adds='+str(self.base_remote_adds[kind])+',Rems='+str(self.base_remote_rems[kind])+')')
                    else:
                        printer.println('Base Remote '+kind+' (Refs='+str(refs)+')')
        if kind == RESOURCE_REF_KIND and self.base_resource_refs:
            for kind,refs in self.base_resource_refs.iteritems():
                if refs == 0:
                    if verbose:
                        printer.println('Empty (Refs=0): Base Resource '+kind+
                            ' (Adds='+str(self.base_resource_adds[kind])+',Rems='+str(self.base_resource_rems[kind])+')')
                else:
                    if verbose:
                        printer.println('NON-EMPTY (Refs='+str(refs)+'): Base Resource '+kind+
                            ' (Adds='+str(self.base_resource_adds[kind])+',Rems='+str(self.base_resource_rems[kind])+')')
                    else:
                        printer.println('Base Resource '+kind+' (Refs='+str(refs)+')')
        if kind == GC_REF_KIND and self.nested_gc_refs:
            for src,refs in self.nested_gc_refs.iteritems():
                if refs == 0:
                    if verbose:
                        printer.println('Empty (Refs=0): Nested GC '+repr(src)+
                            ' (Adds='+str(self.nested_gc_adds[src])+',Rems='+str(self.nested_gc_rems[src])+')')
                    continue
                if verbose:
                    printer.println('NON-EMPTY (Refs='+str(refs)+'): Nested GC '+repr(src)+
                        ' (Adds='+str(self.nested_gc_adds[src])+',Rems='+str(self.nested_gc_rems[src])+')')
                else:
                    printer.println('Nested GC '+repr(src)+' (Refs='+str(refs)+')')
                printer.down()
                src.report_references(printer, kind, verbose)
                printer.up()
        if kind == VALID_REF_KIND and self.nested_valid_refs:
            for src,refs in self.nested_valid_refs.iteritems():
                if refs == 0:
                    if verbose:
                        printer.println('Empty (Refs=0): Nested Valid '+repr(src)+
                            ' (Adds='+str(self.nested_valid_adds[src])+',Rems='+str(self.nested_valid_rems[src])+')')
                    continue
                if verbose:
                    printer.println('NON-EMPTY (Refs='+str(refs)+'): Nested Valid '+repr(src)+
                        ' (Adds='+str(self.nested_valid_adds[src])+',Rems='+str(self.nested_valid_rems[src])+')')
                else:
                    printer.println('Nested Valid '+repr(src)+' (Refs='+str(refs)+')')
                printer.down()
                src.report_references(printer, kind, verbose)
                printer.up()
        if kind == REMOTE_REF_KIND and self.nested_remote_refs:
            for src,refs in self.nested_remote_refs.iteritems():
                if refs == 0:
                    if verbose:
                        printer.println('Empty (Refs=0): Nested Remote '+repr(src)+
                            ' (Adds='+str(self.nested_remote_adds[src])+',Rems='+str(self.nested_remote_rems[src])+')')
                    continue
                if verbose:
                    printer.println('NON-EMPTY (Refs='+str(refs)+'): Nested Remote '+repr(src)+
                        ' (Adds='+str(self.nested_remote_adds[src])+',Rems='+str(self.nested_remote_rems[src])+')')
                else:
                    printer.println('Nested Remote '+repr(src)+' (Refs='+str(refs)+')')
                printer.down()
                src.report_references(printer, kind, verbose)
                printer.up()
        if kind == RESOURCE_REF_KIND and self.nested_resource_refs:
            for src,refs in self.nested_resource_refs.iteritems():
                if refs == 0:
                    if verbose:
                        printer.println('Empty (Refs=0): Nested Resource '+repr(src)+
                            ' (Adds='+str(self.nested_resource_adds[src])+',Rems='+str(self.nested_resource_rems[src])+')')
                    continue
                if verbose:
                    printer.println('NON-EMPTY (Refs='+str(refs)+'): Nested Resource '+repr(src)+
                        ' (Adds='+str(self.nested_resource_adds[src])+',Rems='+str(self.nested_resource_rems[src])+')')
                else:
                    printer.println('Nested Resource '+repr(src)+' (Refs='+str(refs)+')')
                printer.down()
                src.report_references(printer, kind, verbose)
                printer.up()
        printer.up()
        return False

    def check_for_cycles(self):
        stack = list()
        self.check_for_cycles_by_kind(stack, GC_REF_KIND)
        stack = list()
        self.check_for_cycles_by_kind(stack, VALID_REF_KIND)
        stack = list()
        self.check_for_cycles_by_kind(stack, REMOTE_REF_KIND)
        stack = list()
        self.check_for_cycles_by_kind(stack, RESOURCE_REF_KIND)

    def check_for_cycles_by_kind(self, stack, kind):
        if self.on_stack:
            print 'CYCLE DETECTED!'
            for obj in stack:
                print '  '+repr(obj)
            print 'Exiting...'
            sys.exit(0)
        stack.append(self)
        self.on_stack = True
        if kind == GC_REF_KIND and self.nested_gc_refs:
            for src,refs in self.nested_gc_refs.iteritems():
                if refs is 0:
                    continue
                src.check_for_cycles_by_kind(stack, kind)
        if kind == VALID_REF_KIND and self.nested_valid_refs:
            for src,refs in self.nested_valid_refs.iteritems():
                if refs is 0:
                    continue
                src.check_for_cycles_by_kind(stack, kind)
        if kind == REMOTE_REF_KIND and self.nested_remote_refs:
            for src,refs in self.nested_remote_refs.iteritems():
                if refs is 0:
                    continue
                src.check_for_cycles_by_kind(stack, kind)
        if kind == RESOURCE_REF_KIND and self.nested_resource_refs:
            for src,refs in self.nested_resource_refs.iteritems():
                if refs is 0:
                    continue
                src.check_for_cycles_by_kind(stack, kind)
        stack.pop()
        self.on_stack = False

class Manager(Base):
    def __init__(self, did, node):
        super(Manager,self).__init__(did, node)
        self.instance = None

    def add_inst(self, inst):
        self.instance = inst

    def __repr__(self):
        result = 'Manager '+str(self.did)+' (Node='+str(self.node)+')'
        if self.instance is not None:
            result += ' '+repr(self.instance)
        return result

class View(Base):
    def __init__(self, did, node, kind):
        super(View,self).__init__(did, node)
        self.kind = kind
        self.manager = None

    def add_manager(self, manager):
        self.manager = manager

    def __repr__(self):
        result = self.kind +' View '+str(self.did)+' (Node='+str(self.node)+')'
        return result

class Future(Base):
    def __init__(self, did, node):
        super(Future,self).__init__(did, node)

    def __repr__(self):
        return 'Future '+str(self.did)+' (Node='+str(self.node)+')'

class VersionState(Base):
    def __init__(self, did, node):
        super(VersionState,self).__init__(did, node)

    def __repr__(self):
        return 'Version State '+str(self.did)+' (Node='+str(self.node)+')'

class Constraints(Base):
    def __init__(self, did, node):
        super(Constraints,self).__init__(did, node)

    def __repr__(self):
        return 'Layout Constraints '+str(self.did)+' (Node='+str(self.node)+')'

class Instance(object):
    def __init__(self, iid, mem, kind):
        self.iid = iid
        self.mem = mem
        self.kind = kind

    def __repr__(self):
        return self.kind + ' Instance '+hex(self.iid)

class State(object):
    def __init__(self):
        self.managers = {}
        self.views = {}
        self.futures = {}
        self.unknowns = {}
        self.instances = {}
        self.src_names = {}
        self.constraints = {}
        self.version_states = {}

    def parse_log_file(self, file_name):
        with open(file_name, 'rb') as log:
            matches = 0
            for line in log:
                matches += 1
                m = add_base_ref_pat.match(line)
                if m is not None:
                    self.log_add_base_ref(int(m.group('kind')),
                                          long(m.group('did')),
                                          long(m.group('node')),
                                          int(m.group('src')),
                                          int(m.group('cnt')))
                    continue
                m = add_nested_ref_pat.match(line)
                if m is not None:
                    self.log_add_nested_ref(int(m.group('kind')),
                                            long(m.group('did')),
                                            long(m.group('node')),
                                            long(m.group('src')),
                                            int(m.group('cnt')))
                    continue
                m = remove_base_ref_pat.match(line)
                if m is not None:
                    self.log_remove_base_ref(int(m.group('kind')),
                                             long(m.group('did')),
                                             long(m.group('node')),
                                             int(m.group('src')),
                                             int(m.group('cnt')))
                    continue
                m = remove_nested_ref_pat.match(line)
                if m is not None:
                    self.log_remove_nested_ref(int(m.group('kind')),
                                               long(m.group('did')),
                                               long(m.group('node')),
                                               long(m.group('src')),
                                               int(m.group('cnt')))
                    continue
                m = inst_manager_pat.match(line)
                if m is not None:
                    self.log_inst_manager(long(m.group('did')),
                                          long(m.group('node')),
                                          long(m.group('iid'),16),
                                          long(m.group('mem'),16))
                    continue
                m = list_manager_pat.match(line)
                if m is not None:
                    self.log_list_manager(long(m.group('did')),
                                          long(m.gropu('node')),
                                          long(m.group('iid'),16),
                                          long(m.group('mem'),16))
                    continue
                m = fold_manager_pat.match(line)
                if m is not None:
                    self.log_fold_manager(long(m.group('did')),
                                          long(m.group('node')),
                                          long(m.group('iid'),16),
                                          long(m.group('mem'),16))
                    continue
                m = materialize_pat.match(line)
                if m is not None:
                    self.log_materialized_view(long(m.group('did')),
                                               long(m.group('node')),
                                               long(m.group('inst')))
                    continue
                m = composite_pat.match(line)
                if m is not None:
                    self.log_composite_view(long(m.group('did')),
                                            long(m.group('node')))
                    continue
                m = fill_pat.match(line)
                if m is not None:
                    self.log_fill_view(long(m.group('did')),
                                       long(m.group('node')))
                    continue
                m = reduction_pat.match(line)
                if m is not None:
                    self.log_reduction_view(long(m.group('did')),
                                            long(m.group('node')),
                                            long(m.group('inst')))
                    continue
                m = version_state_pat.match(line)
                if m is not None:
                    self.log_version_state(long(m.group('did')),
                                           long(m.group('node')))
                    continue
                m = future_pat.match(line)
                if m is not None:
                    self.log_future(long(m.group('did')),
                                    long(m.group('node')))
                    continue
                m = constraints_pat.match(line)
                if m is not None:
                    self.log_constraints(long(m.group('did')),
                                         long(m.group('node')))
                    continue
                m = source_kind_pat.match(line)
                if m is not None:
                    self.log_source_kind(int(m.group('kind')),
                                         m.group('name'))
                    continue
                m = deletion_pat.match(line)
                if m is not None:
                    self.log_deletion(long(m.group('did')),
                                      long(m.group('node')))
                    continue
                matches -= 1
                print 'Skipping unmatched line: '+line
        return matches

    def post_parse(self):
        # Delete the virtual instance it is special
        to_del = list()
        for key,val in self.unknowns.iteritems():
            if key[0] == 0:
                to_del.append(key)
        for key in to_del:
            del self.unknowns[key]
        if self.unknowns:
            print "WARNING: Found %d unknown objects!" % len(self.unknowns)
            for did in self.unknowns.iterkeys():
                print '  Unknown DID '+str(hex(did[0]))+' on node '+str(did[1])
        # Now update all the pointers to references
        for man in self.managers.itervalues():
            man.update_nested_references(self)
        for view in self.views.itervalues():
            view.update_nested_references(self)
        for future in self.futures.itervalues():
            future.update_nested_references(self)
        for constraint in self.constraints.itervalues():
            constraint.update_nested_references(self)
        for state in self.version_states.itervalues():
            state.update_nested_references(self)
        # Run the garbage collector
        gc.collect()

    def log_add_base_ref(self, kind, did, node, src, cnt):
        obj = self.get_obj(did, node)
        assert src in self.src_names
        obj.add_base_ref(kind, self.src_names[src], cnt)

    def log_add_nested_ref(self, kind, did, node, src, cnt):
        obj = self.get_obj(did, node)
        obj.add_nested_ref(kind, src, cnt)

    def log_remove_base_ref(self, kind, did, node, src, cnt):
        obj = self.get_obj(did, node)
        assert src in self.src_names
        obj.remove_base_ref(kind, self.src_names[src], cnt)

    def log_remove_nested_ref(self, kind, did, node, src, cnt):
        obj = self.get_obj(did, node)
        obj.remove_nested_ref(kind, src, cnt)

    def log_inst_manager(self, did, node, iid, mem):
        inst = self.get_instance(iid, mem, 'Physical')
        manager = self.get_manager(did, node)
        manager.add_inst(inst)

    def log_list_manager(self, did, node, iid, mem):
        inst = self.get_instance(iid, mem, 'List Reduction')
        manager = self.get_manager(did, node)
        manager.add_inst(inst)

    def log_fold_manager(self, did, node, iid, mem):
        inst = self.get_instance(iid, mem, 'Fold Reduction')
        manager = self.get_manager(did, node)
        manager.add_inst(inst)

    def log_materialized_view(self, did, node, inst):
        manager = self.get_manager(inst, node)
        view = self.get_view(did, node, 'Materialized')
        view.add_manager(manager)

    def log_composite_view(self, did, node):
        self.get_view(did, node, 'Composite')

    def log_fill_view(self, did, node):
        self.get_view(did, node, 'Fill')

    def log_reduction_view(self, did, node, inst):
        manager = self.get_manager(inst, node)
        view = self.get_view(did, node, 'Reduction')
        view.add_manager(manager)

    def log_version_state(self, did, node):
        self.get_version_state(did, node);

    def log_future(self, did, node):
        self.get_future(did, node)

    def log_constraints(self, did, node):
        self.get_constraints(did, node)

    def log_source_kind(self, kind, name):
        if kind not in self.src_names:
            self.src_names[kind] = name

    def log_deletion(self, did, node):
        obj = self.get_obj(did, node)
        obj.deleted = True

    def get_instance(self, iid, mem, kind):
        if iid not in self.instances:
            self.instances[iid] = Instance(iid, mem, kind)
        return self.instances[iid]

    def get_manager(self, did, node):
        key = (did,node)
        if key not in self.managers:
            self.managers[key] = Manager(did, node)
            if key in self.unknowns:
                self.managers[key].clone(self.unknowns[key])
                del self.unknowns[key]
        return self.managers[key]

    def get_view(self, did, node, kind):
        key = (did,node)
        if key not in self.views:
            self.views[key] = View(did, node, kind)
            if key in self.unknowns:
                self.views[key].clone(self.unknowns[key])
                del self.unknowns[key]
        return self.views[key]

    def get_version_state(self, did, node):
        key = (did,node)
        if key not in self.version_states:
            self.version_states[key] = VersionState(did, node)
            if key in self.unknowns:
                self.version_states[key].clone(self.unknowns[key])
                del self.unknowns[key]
        return self.version_states[key]

    def get_future(self, did, node):
        key = (did,node)
        if key not in self.futures:
            self.futures[key] = Future(did, node)
            if key in self.unknowns:
                self.futures[key].clone(self.unknowns[key])
                del self.unknowns[key]
        return self.futures[key]

    def get_constraints(self, did, node):
        key = (did,node)
        if key not in self.constraints:
            self.constraints[key] = Constraints(did, node)
            if key in self.unknowns:
                self.constraints[key].clone(self.unknowns[key])
                del self.unknowns[key]
        return self.constraints[key]

    def get_obj(self, did, node):
        key = (did,node)
        if key in self.views:
            return self.views[key]
        if key in self.managers:
            return self.managers[key]
        if key in self.futures:
            return self.futures[key]
        if key in self.version_states:
            return self.version_states[key]
        if key in self.constraints:
            return self.constraints[key]
        if key in self.unknowns:
            return self.unknowns[key]
        self.unknowns[key] = Base(did, node)
        return self.unknowns[key]

    def check_for_cycles(self):
        for did,manager in self.managers.iteritems():
            print "Checking for cycles in "+repr(manager)
            manager.check_for_cycles()
        for did,view in self.views.iteritems():
            print "Checking for cycles in "+repr(view)
            view.check_for_cycles()
        for did,future in self.futures.iteritems():
            print "Checking for cycles in "+repr(future)
            future.check_for_cycles()
        for did,version in self.version_states.iteritems():
            print "Checking for cycles in "+repr(version)
            version.check_for_cycles()
        for did,constraint in self.constraints.iteritems():
            print "Checking for cycles in "+repr(constraint)
            constraint.check_for_cycles()
        print "NO CYCLES"

    def check_for_leaks(self, verbose):
        leaked_futures = 0
        leaked_constraints = 0
        leaked_managers = 0
        pinned_managers = 0
        leaked_views = 0
        leaked_states = 0
        for future in self.futures.itervalues():
            if not future.check_for_leaks(verbose):
                leaked_futures += 1
        for constraint in self.constraints.itervalues():
            if not constraint.check_for_leaks(verbose):
                leaked_constraints += 1
        for manager in self.managers.itervalues():
            deleted,pinned = manager.check_for_leaks(verbose)
            if not deleted:
                if pinned:
                    pinned_managers += 1
                else:
                    leaked_managers += 1
        for view in self.views.itervalues():
            if not view.check_for_leaks(verbose):
                leaked_views += 1
        for state in self.version_states.itervalues():
            if not state.check_for_leaks(verbose):
                leaked_states += 1
        print "LEAK SUMMARY"
        if leaked_futures > 0:
            print "  LEAKED_FUTURES: "+str(leaked_futures)
        else:
            print "  Leaked Futures: "+str(leaked_futures)
        if leaked_constraints > 0:
            print "  LEAKED CONSTRAINTS: "+str(leaked_constraints)
        else:
            print "  Leaked Constraints: "+str(leaked_constraints)
        if leaked_managers > 0:
            print "  LEAKED MANAGERS: "+str(leaked_managers)
        else:
            print "  Leaked Managers: "+str(leaked_managers)
        if pinned_managers > 0:
            print "  PINNED MANAGERS: "+str(pinned_managers)
        else:
            print "  Pinned Managers: "+str(pinned_managers)
        if leaked_views > 0:
            print "  LEAKED VIEWS: "+str(leaked_views)
        else:
            print "  Leaked Views: "+str(leaked_views)
        if leaked_states > 0:
            print "  LEAKED VERSION STATES: "+str(leaked_states)
        else:
            print "  Leaked Version States: "+str(leaked_states)

def usage():
    print 'Usage: '+sys.argv[0]+' [-c -l -v] <file_names>+'
    print '  -c : check for cycles'
    print '  -l : check for leaks'
    print '  -v : verbose'
    sys.exit(1)

def main():
    opts, args = getopt(sys.argv[1:],'clv')
    opts = dict(opts)
    if len(args) == 0:
        usage()
    check_cycles = False
    check_leaks = False
    verbose = False
    if '-c' in opts:
        check_cycles = True
    if '-l' in opts:
        check_leaks = True
    if '-v' in opts:
        verbose = True

    file_names = args

    state = State()
    has_matches = False
    for file_name in file_names:
        print 'Reading log file %s...' % file_name
        total_matches = state.parse_log_file(file_name)
        print 'Matched %s lines' % total_matches
        if total_matches > 0:
            has_matches = True
    if not has_matches:
        print 'No matches found! Exiting...'
        return

    state.post_parse()

    if check_cycles:
        state.check_for_cycles()
    if check_leaks:
        state.check_for_leaks(verbose)

if __name__ == '__main__':
    main()


text:
extern crate getopts;
extern crate debug;

use std::collections::HashMap;
use std::os;
use std::from_str::FromStr;
use std::to_str::ToStr;

use getopts::{usage,getopts,OptGroup};
use getopts::Fail_;

/// The settings structure we save the options and settings in.
pub struct Settings {
  store: HashMap<String,String>,
  options: Box<Vec<OptGroup>>,
}

impl Settings {
  /// Create a new Settings struct.
  pub fn new() -> Settings {
    Settings { store: HashMap::new(), options: box Vec::new() }
  }

  /// Set a settings key to a value. The value will be serialized.
  pub fn set<A: ToStr, T: ToStr>(&mut self, setting: A, value: T) {
    self.store.swap(setting.to_str(), value.to_str());
  }

  /// Set a value using an Option struct. The value will only be set if the
  /// value is not None. This way, you can avoid unwrapping the result of a
  /// previous operation by yourself.
  pub fn set_opt<A: ToStr, T: ToStr>(&mut self, setting: A, value: Option<T>) {
    if value.is_some() {
      self.store.swap(setting.to_str(), value.unwrap().to_str());
    }
  }

  /// Fetch a setting for a key. Fails if the setting is present but could not be
  /// parsed.
  pub fn fetch<A: ToStr, T: FromStr>(&self, setting: A) -> Option<T> {
    match self.store.find(&setting.to_str()) {
      Some(string) => {
        let value = from_str(string.as_slice());
        if value.is_none() {
          fail!("setting could not be parsed: {:?}", setting.to_str())
        }
        value
      },
      None => { None }
    }
  }

  /// Fetch a setting for a key and pass it to the given function. The result of the function
  /// will be returned.
  pub fn fetch_with<A: ToStr, T: FromStr>(&self, setting: A, f: |Option<T>| -> T) -> T {
    let value = self.fetch(setting.to_str());
    f(value)
  }

  /// Register a commandline for later use with load_args.
  ///
  /// Currently, only optopt and reqopt are properly supported.
  pub fn opt(&mut self, opt: OptGroup) {
    self.options.push(opt);
  }

  /// Load the command line argument given by the OS.
  ///
  /// Optionally returns failures.
  pub fn load_os_args(&mut self) -> Option<Fail_> {
    self.load_args(os::args())
  }

  /// Load a list of command line arguments.
  ///
  /// Automatically sets "knob.progname" to the name of the program.
  ///
  /// Optionally returns failures.
  pub fn load_args(&mut self, args: Vec<String>) -> Option<Fail_> {
    let ref prog_name = args.get(0);

    self.set("knob.progname", prog_name.clone());

    let matches = match getopts(args.tail(), self.options.as_slice()) {
      Ok(m) => { m }
      Err(fail) => { return Some(fail) }
    };

    let given_options = self.options.clone();
    for opt in given_options.iter() {
      let opt_strings = &[opt.short_name.clone(), opt.long_name.clone()];
      self.set_opt(opt.long_name.clone(), matches.opts_str(opt_strings))
    };
    None
  }

  /// Returns the usage string for the stored OptGroups. Pass `brief`
  /// to have a brief message included before the usage strings.
  pub fn usage(&self, brief: String) -> String {
    usage(brief.as_slice(), self.options.as_slice())
  }
}


text:
<configuration>
    <appender name="rollingLog" class="ch.qos.logback.core.rolling.RollingFileAppender">
        <file>log/app.log</file>
        <encoder>
            <pattern>%date [%thread] %level %logger{15} - %message %n</pattern>
        </encoder>
        <rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
            <fileNamePattern>log/app.%d{yyyy-MM-dd}.log</fileNamePattern>
            <maxHistory>10</maxHistory>
        </rollingPolicy>
    </appender>

    <root level="INFO">
        <appender-ref ref="rollingLog"/>
    </root>
</configuration>


text:
@interface ExampleRecycledViewWithDrawRect : UIView

@end


text:
'use strict';

import 'vs/css!./media/outputactions.contribution';
import nls = require('vs/nls');
import {BaseActionItem} from 'vs/base/browser/ui/actionbar/actionbar';
import {SyncActionDescriptor} from 'vs/platform/actions/common/actions';
import {IWorkbenchActionRegistry, Extensions as ActionExtensions} from 'vs/workbench/browser/actionRegistry';
import {Registry} from 'vs/platform/platform';
import {CommonEditorRegistry, EditorActionDescriptor} from 'vs/editor/common/editorCommonExtensions';
import {Scope, IActionBarRegistry, Extensions as ActionBarExtensions} from 'vs/workbench/browser/actionBarRegistry';
import {Action} from 'vs/base/common/actions';
import {IEditorInputAction, IEditorInputActionContext, EditorInputActionContributor} from 'vs/workbench/browser/parts/editor/baseEditor';
import {OutputEditorInput} from 'vs/workbench/parts/output/browser/outputEditorInput';
import {ClearOutputEditorAction, ToggleOutputAction, GlobalShowOutputAction, SwitchOutputActionItem, SwitchOutputAction, ClearOutputAction} from 'vs/workbench/parts/output/browser/outputActions';
import {IInstantiationService} from 'vs/platform/instantiation/common/instantiation';
import {KeyMod, KeyCode} from 'vs/base/common/keyCodes';

class OutputEditorActionContributor extends EditorInputActionContributor {

	constructor( @IInstantiationService private instantiationService: IInstantiationService) {
		super();
	}

	public hasActionsForEditorInput(context: IEditorInputActionContext): boolean {
		return context.input instanceof OutputEditorInput;
	}

	public getActionsForEditorInput(context: IEditorInputActionContext): IEditorInputAction[] {
		let actions: IEditorInputAction[] = [];

		actions.push(this.instantiationService.createInstance(SwitchOutputAction));
		actions.push(this.instantiationService.createInstance(ClearOutputAction));

		return actions;
	}

	public getActionItem(context: any, action: Action): BaseActionItem {
		if (action.id === SwitchOutputAction.ID) {
			return this.instantiationService.createInstance(SwitchOutputActionItem, action, context.input);
		}

		return super.getActionItem(context, action);
	}
}

let actionRegistry = <IWorkbenchActionRegistry>Registry.as(ActionExtensions.WorkbenchActions);
let actionBarRegistry = <IActionBarRegistry>Registry.as(ActionBarExtensions.Actionbar);

// register show output action globally
actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(GlobalShowOutputAction, GlobalShowOutputAction.ID, GlobalShowOutputAction.LABEL), nls.localize('viewCategory', "View"));

actionRegistry.registerWorkbenchAction(new SyncActionDescriptor(ToggleOutputAction, ToggleOutputAction.ID, ToggleOutputAction.LABEL, {
	primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_U,
	linux: {
		primary: KeyMod.CtrlCmd | KeyMod.Shift | KeyCode.KEY_H  // On Ubuntu Ctrl+Shift+U is taken by some global OS command
	}
}), nls.localize('viewCategory', "View"));

// Contribute Output Editor Contributor
actionBarRegistry.registerActionBarContributor(Scope.EDITOR, OutputEditorActionContributor);

// Contribute to Context Menu of Output Window
CommonEditorRegistry.registerEditorAction(new EditorActionDescriptor(ClearOutputEditorAction, ClearOutputEditorAction.ID, nls.localize('clearOutput.label', "Clear Output")));


text:
package nodjo.plugin.xkcd;

import java.io.IOException;
import java.util.HashMap;

import nodjo.fcr.comics.IComic;
import nodjo.fcr.utils.StreamUtils;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.HttpStatus;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.conn.scheme.PlainSocketFactory;
import org.apache.http.conn.scheme.Scheme;
import org.apache.http.conn.scheme.SchemeRegistry;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.impl.conn.tsccm.ThreadSafeClientConnManager;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.os.RemoteException;
import android.util.Log;

public class Xkcd extends Service {

    private static final String TAG = Xkcd.class.getSimpleName();

    private static final String SERVER_URL = "http://www.xkcd.com/";
    private static final String SERVER_URL_JSON = "info.0.json";
    private static final String ONLINE_STORE_URL = "http://store.xkcd.com/?source=fastcomicreader";

    private static final HttpParams HTTP_PARAMS = new BasicHttpParams();
    static {
        HttpConnectionParams.setConnectionTimeout(HTTP_PARAMS, 15000);
        HttpConnectionParams.setSoTimeout(HTTP_PARAMS, 30000);
    }
    private ThreadSafeClientConnManager mConnectionManager;

    @Override
    public IBinder onBind(Intent intent) {
        final SchemeRegistry registry = new SchemeRegistry();
        registry.register(new Scheme("http", PlainSocketFactory.getSocketFactory(), 80));
        mConnectionManager = new ThreadSafeClientConnManager(HTTP_PARAMS, registry);
        return mBinder;
    }

    private final IComic.Stub mBinder = new IComic.Stub() {

        class TitleUrl {

            private final String title;
            private final String url;

            private TitleUrl(String title, String url) {
                this.title = title;
                this.url = url;
            }
        }

        private final HashMap<Long, TitleUrl> cache = new HashMap<Long, TitleUrl>();

        @Override
        public long[] getStripIdentifiers() throws RemoteException {
            Log.v(TAG, "getStripIdentifiers");
            final HttpClient httpClient = new DefaultHttpClient(mConnectionManager, HTTP_PARAMS);
            HttpResponse response;
            HttpGet httpGet = new HttpGet(SERVER_URL + SERVER_URL_JSON);
            try {
                response = httpClient.execute(httpGet);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    Log.d(TAG, "html size:" + entity.getContentLength() + " bytes");
                    final String jsonContent = StreamUtils.convertStreamToString(entity.getContent(), (int) entity.getContentLength());
                    final JSONObject json = new JSONObject(jsonContent);
                    final int currentId = json.getInt("num");
                    final long[] ids = new long[currentId];
                    for (int i = 0; i < currentId; i++)
                        ids[i] = i + 1;
                    Log.i(TAG, "returning:" + ids);
                    return ids;
                } else {
                    Log.w(TAG, "Connection problem. Response status code:" + response.getStatusLine().getStatusCode());
                }
            } catch (ClientProtocolException e) {
                Log.w(TAG, "ClientProtocolException", e);
            } catch (IOException e) {
                Log.w(TAG, "IOException", e);
            } catch (JSONException e) {
                Log.w(TAG, "JSONException", e);
            }
            return null;
        }

        @Override
        public String getStripUrl(long stripId) throws RemoteException {
            Log.v(TAG, "getStripUrl:" + stripId);
            if (!cache.containsKey(stripId))
                cache.put(stripId, getTitleUrl(stripId));
            return cache.get(stripId).url;
        }

        // TODO don't call in main thread so that it can access network...
        @Override
        public String getStripTitle(long stripId) throws RemoteException {
            Log.v(TAG, "getStripTitle:" + stripId);
            if (!cache.containsKey(stripId))
                return String.valueOf(stripId);
            // cache.put(stripId, getTitleUrl(stripId));
            return cache.get(stripId).title;
        }

        private TitleUrl getTitleUrl(long stripId) {
            Log.v(TAG, "getTitleUrl:" + stripId);

            final HttpClient httpClient = new DefaultHttpClient(mConnectionManager, HTTP_PARAMS);
            HttpResponse response;
            HttpGet httpGet = new HttpGet(SERVER_URL + stripId + "/" + SERVER_URL_JSON);
            try {
                response = httpClient.execute(httpGet);
                if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) {
                    HttpEntity entity = response.getEntity();
                    Log.d(TAG, "html size:" + entity.getContentLength() + " bytes");
                    final String jsonContent = StreamUtils.convertStreamToString(entity.getContent(), (int) entity.getContentLength());
                    final JSONObject json = new JSONObject(jsonContent);
                    return new TitleUrl(json.getString("safe_title"), json.getString("img"));
                } else {
                    Log.w(TAG, "Connection problem. Response status code:" + response.getStatusLine().getStatusCode());
                }
            } catch (ClientProtocolException e) {
                Log.w(TAG, "ClientProtocolException", e);
            } catch (IOException e) {
                Log.w(TAG, "IOException", e);
            } catch (JSONException e) {
                Log.w(TAG, "JSONException", e);
            }
            return null;
        }

        @Override
        public String getWebsiteUrl() throws RemoteException {
            Log.v(TAG, "getWebsiteUrl");
            return ONLINE_STORE_URL;
        }

    };

    @Override
    public boolean onUnbind(Intent intent) {
        Log.v(TAG, "onUnbind");
        mConnectionManager.shutdown();
        mConnectionManager = null;
        return super.onUnbind(intent);
    }
}


text:
/*
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *     http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */

package com.jrtc27.portallink;

import java.io.*;
import java.util.HashMap;
import java.util.Map;
import java.util.regex.Pattern;

import org.bukkit.ChatColor;
import org.bukkit.World.Environment;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.MemoryConfiguration;

public class ConfigHandler {
	private static final String LINKS_FILE_NAME = "links.properties";
	private static final String LINKS_TEMP_FILE_NAME = LINKS_FILE_NAME + ".tmp";
	private final Pattern LINK_PATTERN = Pattern.compile("(^(?==)|(?<==)(?=[^=])|(?<=[^=])(?==)|(?<==)$)");

	private final PortalLink plugin;

	private final Map<String, LinkEntry> definedLinks = new HashMap<String, LinkEntry>();
	private boolean denyEntityPortal;

	public ConfigHandler(final PortalLink plugin) {
		this.plugin = plugin;
	}

	public Map<String, LinkEntry> getUserDefinedLinks() {
		return this.definedLinks;
	}

	public boolean denyEntityPortal() {
		return this.denyEntityPortal;
	}

	public void load() {
		this.loadConfig();
		this.loadUserDefinedLinks();
	}

	private void loadConfig() {
		this.plugin.saveDefaultConfig();
		final MemoryConfiguration config = this.plugin.getConfig();
		this.denyEntityPortal = config.getBoolean("deny-entity-portal", true);
		this.plugin.checkForUpdates = config.getBoolean("check-updates", true);
	}

	private void loadUserDefinedLinks() {
		this.definedLinks.clear();
		try {
			final BufferedReader in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(this.plugin.getDataFolder(), LINKS_FILE_NAME)), "UTF-8"));
			String s;
			int line = 0;
			while ((s = in.readLine()) != null) {
				line++;
				s = s.trim();
				if (s.isEmpty()) continue;
				if (s.startsWith("#")) continue;
				final String[] args = LINK_PATTERN.split(s, -1); // -1 means we get the trailing space
				if (args.length < 3) {
					this.plugin.logWarning("Missing \"=\" sign(s) on line " + line + " of " + LINKS_FILE_NAME + ".");
					continue;
				} else if (args.length > 3) {
					this.plugin.logWarning("Only one link can be specified per line - ignoring all other links on line " + line + " of " + LINKS_FILE_NAME + ".");
				}
				args[0] = args[0].trim();
				args[2] = args[2].trim();
				boolean twoWay = args[1].equals("==");
				int whichNether = 0;
				if (args[0].startsWith("<") && args[0].endsWith(">")) {
					whichNether |= 1;
					args[0] = args[0].substring(1, args[0].length() - 1);
				}
				if (args[2].startsWith("<") && args[2].endsWith(">")) {
					whichNether |= 2;
					args[2] = args[2].substring(1, args[2].length() - 1);
				}
				this.addLink(args[0], args[2], null, twoWay, whichNether, false);
			}
			in.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			final File directory = this.plugin.getDataFolder();
			if (!directory.isDirectory()) {
				if (!directory.mkdir()) {
					this.plugin.logSevere("Unable to create plugin data directory!");
					return;
				}
			}
			try {
				final Writer out = new OutputStreamWriter(new FileOutputStream(new File(this.plugin.getDataFolder(), LINKS_FILE_NAME)), "UTF-8");
				out.write("# Place any custom links inside this file.\n");
				out.write("# Any world will be automatically linked with its name followed by \"_nether\".\n");
				out.write("# Links should be specified with the format World=<NetherWorld>.\n");
				out.write("# All nether worlds MUST be surrounded by < and > as shown in the above example.\n");
				out.write("# You can link two nether worlds or two normal worlds if desired.\n");
				out.write("# By default all links are one way (left world to right world) - to link them both\n");
				out.write("# ways, change the \"=\" to \"==\".\n");
				out.write("# A blank link will stop a player from being able to use a portal in that world.\n");
				out.write("# Only one link per line (extra links will be ignored).\n");
				out.write("# Later links will override previous ones.\n");
				out.write("# Lines beginning with a hash (\"#\") are treated as comments and so are ignored.\n");
				out.close();
			} catch (UnsupportedEncodingException e1) {
				e1.printStackTrace();
			} catch (FileNotFoundException e1) {
				e1.printStackTrace();
			} catch (IOException e1) {
				e1.printStackTrace();
			}
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void addLink(final String str1, final String str2, final CommandSender sender, final boolean twoWay, int whichNether, final boolean announceCreate) {
		if (!str1.equals("")) {
			if (this.definedLinks.containsKey(str1)) {
				if (sender != null) {
					sender.sendMessage("Overriding previous link for \"" + str1 + "\".");
				}
				this.plugin.logWarning("Overriding previous link for \"" + str1 + "\".");
			}
			this.definedLinks.put(str1, new LinkEntry(str2, whichNether));
		}
		if (announceCreate) {
			if (sender != null) {
				sender.sendMessage("Creating link...");
			}
			this.plugin.logInfo("Creating link...");
		}
		final Environment environmentForWorld1 = (whichNether & 1) == 0 ? Environment.NORMAL : Environment.NETHER;
		final Environment environmentForWorld2 = (whichNether & 2) == 0 ? Environment.NORMAL : Environment.NETHER;
		if (!str1.equals("")) this.plugin.createWorld(str1, environmentForWorld1);
		if (!str2.equals("")) this.plugin.createWorld(str2, environmentForWorld2);
		if (twoWay) {
			whichNether = (whichNether & 1) << 1 | (whichNether & 2) >> 1; // Swap bits 0 and 1
			if (!str2.equals("")) {
				if (this.definedLinks.containsKey(str2)) {
					if (sender != null) {
						sender.sendMessage("Overriding previous link for \"" + str2 + "\".");
					}
					this.plugin.logWarning("Overriding previous link for \"" + str2 + "\".");
				}
				this.definedLinks.put(str2, new LinkEntry(str1, whichNether));
			}
		}
		if (announceCreate) {
			if (sender != null) {
				sender.sendMessage("Created link!");
			}
			this.plugin.logInfo("Created link!");
		}
	}

	public void addLinkAndSave(String str1, String str2, final CommandSender sender, final boolean twoWay, int whichNether) {
		this.addLink(str1, str2, sender, twoWay, whichNether, true);
		if ((whichNether & 1) != 0) {
			str1 = "<" + str1 + ">";
		}
		if ((whichNether & 2) != 0) {
			str2 = "<" + str2 + ">";
		}
		final String outStr = "\n" + str1 + (twoWay ? "==" : "=") + str2;
		try {
			final Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(new File(this.plugin.getDataFolder(), LINKS_FILE_NAME), true), "UTF-8"));
			out.write(outStr);
			out.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			this.plugin.logSevere("The save file could not be accessed!");
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public void removeLink(String str1, String str2, CommandSender sender) {
		BufferedReader in = null;
		Writer out = null;
		boolean removedLink = false;
		try {
			in = new BufferedReader(new InputStreamReader(new FileInputStream(new File(this.plugin.getDataFolder(), LINKS_FILE_NAME)), "UTF-8"));
			out = new OutputStreamWriter(new FileOutputStream(new File(this.plugin.getDataFolder(), LINKS_TEMP_FILE_NAME)), "UTF-8");
			String s;
			while ((s = in.readLine()) != null) {
				final String line = s + "\n";
				s = s.trim();
				if (s.isEmpty() || s.startsWith("#")) {
					out.write(line);
				} else {
					final String[] args = LINK_PATTERN.split(s, -1); // -1 means we get the trailing space
					args[0] = args[0].trim();
					args[2] = args[2].trim();
					boolean twoWay = args[1].equals("==");
					if (args[0].startsWith("<") && args[0].endsWith(">")) {
						args[0] = args[0].substring(1, args[0].length() - 1);
					}
					if (args[2].startsWith("<") && args[2].endsWith(">")) {
						args[2] = args[2].substring(1, args[2].length() - 1);
					}
					if ((args[0].equals(str1) && (args[2].equals(str2) || str2.isEmpty())) || (twoWay && args[0].equals(str2) && args[2].equals(str1))) {
						out.write("# Removed: " + line);
						removedLink = true;
					} else {
						out.write(line);
					}
				}
			}
			in.close();
			out.close();
		} catch (UnsupportedEncodingException e) {
			e.printStackTrace();
		} catch (FileNotFoundException e) {
			if (sender != null) {
				sender.sendMessage(ChatColor.RED + "Unable to find " + LINKS_FILE_NAME + "!");
			}
			this.plugin.logSevere("Unable to find " + LINKS_FILE_NAME + "!");
		} catch (IOException e) {
			e.printStackTrace();
		}
		if (in != null) {
			try {
				in.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (out != null) {
			try {
				out.close();
			} catch (IOException e) {
				e.printStackTrace();
			}
		}
		if (removedLink) {
			final File tempFile = new File(this.plugin.getDataFolder(), LINKS_TEMP_FILE_NAME);
			final File targetFile = new File(this.plugin.getDataFolder(), LINKS_FILE_NAME);
			if (!tempFile.renameTo(targetFile)) {
				if (!targetFile.delete()) {
					// Do nothing
				}
				if (!tempFile.renameTo(targetFile)) {
					this.plugin.logSevere("Unable to rename the temporary file!");
				} else {
					if (sender != null) {
						sender.sendMessage("Link successfully removed!");
					}
					this.plugin.logInfo("Link successfully removed!");
				}
			} else {
				if (sender != null) {
					sender.sendMessage("Link successfully removed!!");
				}
				this.plugin.logInfo("Link successfully removed!");
			}
			this.definedLinks.clear();
			loadUserDefinedLinks();
		} else {
			if (sender != null) {
				sender.sendMessage(ChatColor.RED + "No matching links were found!");
			}
			this.plugin.logWarning("No matching links were found!");
			File tempFile = new File(this.plugin.getDataFolder(), LINKS_TEMP_FILE_NAME);
			if (!tempFile.delete()) {
				this.plugin.logSevere("Unable to delete the temporary file!");
			}
		}
	}
}


text:
<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_pressed="true">
        <shape>
            <solid android:color="@color/content_color_darker" />
            <stroke android:width="@dimen/round_bg_stroke" android:color="@color/content_color" />
            <corners android:radius="@dimen/btn_bg_radius" />
            <padding android:left="@dimen/round_bg_stroke" android:top="@dimen/round_bg_stroke" android:right="@dimen/round_bg_stroke" android:bottom="@dimen/round_bg_stroke" />
        </shape>
    </item>
    <item>
        <shape>
            <solid android:color="@color/content_inner_color" />
            <stroke android:width="@dimen/round_bg_stroke" android:color="@color/content_color" />
            <corners android:radius="@dimen/btn_bg_radius" />
            <padding android:left="@dimen/round_bg_stroke" android:top="@dimen/round_bg_stroke" android:right="@dimen/round_bg_stroke" android:bottom="@dimen/round_bg_stroke" />
        </shape>
    </item>
</selector>


text:
LinqPad driver for LiteDB

[![Build status](https://ci.appveyor.com/api/projects/status/0ckrd3197ggxcny6?svg=true)](https://ci.appveyor.com/project/adospace/litedbpad)

# LinqPad version 4 and 5 (.NET Full)
LiteDbPad is a Dynamic driver for LinqPad. I've tested it in LinqPad 4.x but should work with version 5 just fine.

To install or update LiteDbPad:
1) Download LiteDBPad.lpx
2) in LinqPad Add Connection->More Drivers->Browse to LPX file
Once installed, you should be able to select the driver in the Add Connection dialog.

LiteDbPad can open LiteDB 4.0+ files and let you specify some connection string properties like Password etc.

# LinqPad version 6 (.NET Core)
Install directly from LinqPad:

To open LiteDB version 4 databases:
Add new connection->More Drivers->Show All Drivers->**LiteDBPad6**

To open LiteDB version 5+ databases:
Add new connection->More Drivers->Show All Drivers->**LiteDB5Pad6**

Query database with expressions like

```c#
<mycollectionname>.FindAll()
```


text:
package piazza.services.ingest.model;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.DeserializationContext;
import com.fasterxml.jackson.databind.JsonDeserializer;
import com.fasterxml.jackson.databind.JsonNode;

public class TextKeyValueJsonDeserializer extends JsonDeserializer<List<TextKeyValue>> {

	@Override
	public List<TextKeyValue> deserialize(JsonParser jp, DeserializationContext ctxt)
			throws IOException, JsonProcessingException {
		List<TextKeyValue> textKeyValues = new ArrayList<TextKeyValue>();

		JsonNode root = jp.getCodec().readTree(jp);

		for (int i = 0; i != root.size(); ++i) {

			TextKeyValue keyValue = new TextKeyValue(root.get(i).get("key").asText(),
					root.get(i).get("value").asText());

			textKeyValues.add(keyValue);
		}
		return textKeyValues;
	}

}


text:
Generate Foreign Tables for PostgreSQL
===================================

This generates Foreign table definitions to be loaded into a PostgreSQL
databases to access remote tables in PostgreSQL, Mysql, and SQL Server.

The main program is ``generate_foreign_tables.rb``. This has two required arguments
and three optional arguments.

## Arguments

### Requires

* ``-c <connection_string>`` is a Database URL for specifing connection information.
* ``-n <serer_name>``  is the Foreign Server name to use.

### Optional

* ``-schema <remote_schema>`` is the remote schema to search for tables.
* ``-mv`` causes Materialized Views to be generated as a caching layer on the Foreign Tables.
* ``-debug`` Enable debug output

## Database URL

The required option ``-c`` takes a Database URL as an argument.

Database URLs using the standard URL enocoding for username, password,
hostname, and port. The name of the database and other options are encoded in
the path. The URL scheme is the type of database: postgresql, mysql, or sqlserver.

For a mysql database named ``dbexample`` at DNS hostname ``host`` on port
``1234`` with access credentials of ``user`` and ``password``. This would
written as follows: ``mysql://user:password@host:1234/dbexample``

## Example Usage

### Example Invocation

We assume out Foreign Server name is ``mysql_server``. And we will redirect
the output to file `ft.sql``.

``bundle exec ./generate_foreign_tables.rb -c mysql://user:password@host:1234/dbexample -n mysql_server > ft.sql``


text:
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<meta http-equiv="Content-Type" content="text/xhtml;charset=UTF-8"/>
<meta http-equiv="X-UA-Compatible" content="IE=9"/>
<meta name="generator" content="Doxygen 1.8.6"/>
<title>Timer: Class Members - Variables</title>
<link href="tabs.css" rel="stylesheet" type="text/css"/>

<link href="navtree.css" rel="stylesheet" type="text/css"/>

<link href="search/search.css" rel="stylesheet" type="text/css"/>

<link href="doxygen.css" rel="stylesheet" type="text/css" />

Timer
    2.1

Main Page

Classes

Files

          <input type="text" id="MSearchField" value="Search" accesskey="S"
               onfocus="searchBox.OnSearchFieldFocus(true)"
               onblur="searchBox.OnSearchFieldFocus(false)"
               onkeyup="searchBox.OnSearchFieldChange(event)"/>

Class List

Class Index

Class Members

All

Functions

Variables

Related Functions

 All Classes Files Functions Variables Friends

IS_NON_RECURRING
: Timer

IS_RECURRING
: Timer

m_adapter
: Timer

m_currentTimeMillis
: Timer

m_delayMillis
: Timer

m_isExpiredFlag
: Timer

m_isRecurring
: Timer

m_next
: Timer

m_timer
: TimerContext

m_triggerTimeMillis
: Timer

m_triggerTimeMillisUpperLimit
: Timer

s_instance
: TimerContext

Generated on Thu Jun 26 2014 09:07:56 for Timer by

     1.8.6


text:
local field2D = require "field2D"

math.randomseed(os.time())
local floor = math.floor
local min = math.min
local abs = math.abs
local random = math.random
local twopi = math.pi * 2
local sin, cos = math.sin, math.cos

-- choose the size of the field
local dimx = 160
local dimy = dimx * 3/4 -- (with a 4:3 aspect ratio)

-- allocate the field
local field = field2D.new(dimx, dimy)

-- create a second field, to store the previous states of the cells:
local field_old = field2D.new(dimx, dimy)

local rate = 0.1

local activation_radius = 1
local inhibition_radius = 5

function initialize()
	return math.random()
end

-- use this to initialize the field:
field:set(initialize)

-- the min & max values of the field:
local min = 0
local max = 1

-- convert a cell from the min..max range to the 0..1 range:
function normalize(x, y)
	return (field:get(x, y) - min) / (max - min)
end

-- this is highly inaccurate; this measures a rectangular border, not a circular radius.
function concentration_over_radius(x, y, r)
	local count = 0
	local sum = 0
	for y1 = y-r, y+r do
		for x1 = x-r, x+r do
			sum = sum + field_old:get(x1, y1)
			count = count + 1
		end
	end
	return sum / count
end

function concentration_around_radius(x, y, r)
	-- get r samples:
	local count = random(r*2)
	local sum = 0
	for i = 1, count do
		local a = random() * twopi
		local r1 = random() * r
		local x1, y1 = x + r1*cos(a), y + r1*sin(a)
		sum = sum + field_old:get(x1, y1)
	end
	return sum / count
end

function concentration_at_radius(x, y, r)
	-- check out the neighbors' previous states:
	local N  = field_old:get(x  , y+r)
	local NE = field_old:get(x+r, y+r)
	local E  = field_old:get(x+r, y  )
	local SE = field_old:get(x+r, y-r)
	local S  = field_old:get(x  , y-r)
	local SW = field_old:get(x-r, y-r)
	local W  = field_old:get(x-r, y  )
	local NW = field_old:get(x-r, y+r)
	return (N + NE + E + SE + S + SW + W + NW) / 8
end

function diff_at_radius(x, y, r, c)
	return concentration_over_radius(x, y, r)
		 - concentration_over_radius(x, y, r * 2)
end

-- the rule for an individual cell (at position x, y) in the field:
function reaction(x, y)

	-- check my own previous state:
	local C = field_old:get(x, y)
	local action = diff_at_radius(x, y, random(10))

	if action > 0 then
		return C + rate
	else
		return C - rate
	end
end

-- update the state of the scene (toggle this on and off with spacebar):
function update(dt)
	for i = 1, 1 do
		-- swap field and field_old:
		-- (field now becomes old, and the new field is ready to be written)
		field, field_old = field_old, field

		-- run the simulation:
		field:set(reaction)
	end
	-- make sure all cells are in the 0..1 range
	field:normalize()
end

-- how to render the scene (toggle fullscreen with the Esc key):
function draw()
	-- draw the field:
	field:draw()
end

-- handle keypress events:
function keydown(k)
	if k == "r" then
		-- apply the coin rule to all cells of the field (randomizes)
		field:set(initialize)
	elseif k == "c" then
		field:clear()
	end
end

-- handle mouse events:
function mouse(event, btn, x, y)
	-- clicking & dragging should draw trees into the field:
	if event == "down" or event == "drag" then
		field:set(math.random(), x * field.width, y * field.height)
	end
end


text:
import $ from 'jquery';

console.log("index1", $);


text:
using System.Net;
using System.Net.Http;
using System.Runtime.Remoting.Messaging;
using System.Threading;
using System.Threading.Tasks;
using Nowin;
using Xunit;

namespace NowinTests.ExecutionContext_Tests
{
    public class ExecutionContextFlowing
    {
        private void ResetExecutionContextFlowForTestThread()
        {
            if (ExecutionContext.IsFlowSuppressed())
                ExecutionContext.RestoreFlow();
        }
        [Theory]
        [InlineData(ExecutionContextFlow.SuppressAlways)]
        [InlineData(ExecutionContextFlow.Flow)]
        [InlineData(ExecutionContextFlow.SuppressOnAsync)]
        public void ExecutionContextOnSetupThread(ExecutionContextFlow flow)
        {
            ResetExecutionContextFlowForTestThread();

            CallContext.LogicalSetData("test.data", "test.value");
            var server = new ServerBuilder()
                .SetEndPoint(new IPEndPoint(IPAddress.Loopback, 8082))
                .SetExecutionContextFlow(flow)
                .SetRetrySocketBindingTime(System.TimeSpan.FromSeconds(4))
                .Build();
            server.Start();
            server.Dispose();
            Assert.Equal(
                "test.value",
                CallContext.LogicalGetData("test.data") as string);
        }

        [Theory]
        [InlineData(ExecutionContextFlow.SuppressAlways, null)]
        [InlineData(ExecutionContextFlow.Flow, "test.value")]
        [InlineData(ExecutionContextFlow.SuppressOnAsync, "test.value")]
        public void ExecutionContextFlowFromSetupThread(ExecutionContextFlow flow, string expectedLogicalContextValue)
        {
            ResetExecutionContextFlowForTestThread();

            CallContext.LogicalSetData("test.data", "test.value");

            var server = new ServerBuilder()
                .SetEndPoint(new IPEndPoint(IPAddress.Loopback, 8082))
                .SetExecutionContextFlow(flow)
                .SetRetrySocketBindingTime(System.TimeSpan.FromSeconds(4))
                .Build();
            server.Start();
            server.Dispose();

            var separateThreadValue = Task.Factory.StartNew(() => CallContext.LogicalGetData("test.data") as string);
            //Assert.True(ExecutionContext.IsFlowSuppressed());
            Assert.Equal(expectedLogicalContextValue, separateThreadValue.Result);
        }

        [Theory]
        [InlineData(ExecutionContextFlow.Flow, "test.value")]
        [InlineData(ExecutionContextFlow.SuppressAlways, null)]
        [InlineData(ExecutionContextFlow.SuppressOnAsync, null)]
        public void ExecutionContextFlowToOwinApp(ExecutionContextFlow flow, string expectedValue)
        {
            ResetExecutionContextFlowForTestThread();

            string applicationValue = null;
            CallContext.LogicalSetData("test.data", "test.value");

            var server = new ServerBuilder()
                .SetEndPoint(new IPEndPoint(IPAddress.Loopback, 8082))
                .SetExecutionContextFlow(flow)
                .SetOwinApp(env=> AppReadingLogicalCallContext(out applicationValue))
                .SetRetrySocketBindingTime(System.TimeSpan.FromSeconds(4))
                .Build();
            server.Start();
            using (var httpClient = new HttpClient())
            {
                var response = httpClient.GetAsync("http://localhost:8082").Result;
            }
            server.Dispose();

            Assert.Equal(expectedValue, applicationValue);
        }

        private static Task AppReadingLogicalCallContext(out string applicationValue)
        {
            applicationValue = CallContext.LogicalGetData("test.data") as string;
            return Task.FromResult(0);
        }
    }
}


text:
package com.jeecms.cms.manager.assist;

import java.util.List;

import com.jeecms.common.page.Pagination;
import com.jeecms.cms.entity.assist.CmsPlug;

public interface CmsPlugMng {
	public Pagination getPage(int pageNo, int pageSize);

	public List<CmsPlug> getList(String author,Boolean used);

	public CmsPlug findById(Integer id);

	public CmsPlug findByPath(String plugPath);

	public CmsPlug save(CmsPlug bean);

	public CmsPlug update(CmsPlug bean);

	public CmsPlug deleteById(Integer id);

	public CmsPlug[] deleteByIds(Integer[] ids);
}


text:
<?php

namespace OSS\Tests;

require_once __DIR__ . '/Common.php';

use OSS\OssClient;

class OssClinetImageTest extends TestOssClientBase
{
    private $bucketName;
    private $client;
    private $local_file;
    private $object;
    private $download_file;

    protected function setUp(): void
    {
        parent::setUp();

        $this->client = $this->ossClient;
        $this->bucketName = $this->bucket;
        $this->local_file = "example.jpg";
        $this->object = "oss-example.jpg";
        $this->download_file = "image.jpg";

        Common::waitMetaSync();
        $this->client->uploadFile($this->bucketName, $this->object, $this->local_file);
    }

    protected function tearDown(): void
    {
        parent::tearDown();
        unlink($this->download_file);
    }

    public function testImageResize()
    {
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $this->download_file,
            OssClient::OSS_PROCESS => "image/resize,m_fixed,h_100,w_100", );
        $this->check($options, 100, 100, 3267, 'jpg');
    }

    public function testImageCrop()
    {
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $this->download_file,
            OssClient::OSS_PROCESS => "image/crop,w_100,h_100,x_100,y_100,r_1", );
        $this->check($options, 100, 100, 1969, 'jpg');
    }

    public function testImageRotate()
    {
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $this->download_file,
            OssClient::OSS_PROCESS => "image/rotate,90", );
        $this->check($options, 267, 400, 20998, 'jpg');
    }

    public function testImageSharpen()
    {
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $this->download_file,
            OssClient::OSS_PROCESS => "image/sharpen,100", );
        $this->check($options, 400, 267, 23015, 'jpg');
    }

    public function testImageWatermark()
    {
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $this->download_file,
            OssClient::OSS_PROCESS => "image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ", );
        $this->check($options, 400, 267, 26369, 'jpg');
    }

    public function testImageFormat()
    {
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $this->download_file,
            OssClient::OSS_PROCESS => "image/format,png", );
        $this->check($options, 400, 267, 160733, 'png');
    }

    public function testImageTofile()
    {
        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $this->download_file,
            OssClient::OSS_PROCESS => "image/resize,m_fixed,w_100,h_100", );
        $this->check($options, 100, 100, 3267, 'jpg');
    }

    public function testProcesObject()
    {
        $object = 'process-object.jpg';
        $process = 'image/resize,m_fixed,w_100,h_100'.
                   '|sys/saveas'.
                   ',o_'.$this->base64url_encode($object).
                   ',b_'.$this->base64url_encode($this->bucketName);
        $result = $this->client->processObject($this->bucketName, $this->object, $process);
        $this->assertTrue(stripos($result, '"object": "process-object.jpg",') > 0);
        $this->assertTrue(stripos($result, '"status": "OK"') > 0);

        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $this->download_file,
        );
        $this->client->getObject($this->bucketName, $object, $options);
        $array = getimagesize($this->download_file);
        $this->assertEquals(100, $array[0]);
        $this->assertEquals(100, $array[1]);
        $this->assertEquals(2, $array[2]);

        //without bucket
        $object = 'process-object-1.jpg';
        $process = 'image/watermark,text_SGVsbG8g5Zu-54mH5pyN5YqhIQ'.
                   '|sys/saveas'.
                   ',o_'.$this->base64url_encode($object);
        $result = $this->client->processObject($this->bucketName, $this->object, $process);
        $this->assertTrue(stripos($result, '"object": "process-object-1.jpg",') > 0);
        $this->assertTrue(stripos($result, '"status": "OK"') > 0);

        $options = array(
            OssClient::OSS_FILE_DOWNLOAD => $this->download_file,
        );
        $this->client->getObject($this->bucketName, $object, $options);
        $array = getimagesize($this->download_file);
        $this->assertEquals(400, $array[0]);
        $this->assertEquals(267, $array[1]);
        $this->assertEquals(2, $array[2]);
    }

    private function check($options, $width, $height, $size, $type)
    {
        $this->client->getObject($this->bucketName, $this->object, $options);
        $array = getimagesize($this->download_file);
        $this->assertEquals($width, $array[0]);
        $this->assertEquals($height, $array[1]);
        $this->assertEquals($type === 'jpg' ? 2 : 3, $array[2]);//2 <=> jpg
    }

    private function base64url_encode($data)
    {
        return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
    }
}