text:
using tsxx::system::memory_region;

memory_region::memory_region(file_descriptor_ptr fd)
{
	if (fd.get() == NULL || !fd->is_valid())
		throw tsxx::exceptions::stdio_error(EINVAL);

	this->fd = fd;
	pointer = MAP_FAILED;
	length = 0;
}

memory_region::~memory_region()
{
	unmap();
}

bool
memory_region::map(std::size_t len, off_t offset)
{
	if (pointer != MAP_FAILED) {
		errno = EBADF;
		return false;
	}

	pointer = ::mmap(0, len, PROT_READ|PROT_WRITE, MAP_SHARED, fd->get_value(), offset);
	if (pointer == MAP_FAILED)
		return false;

	length = len;

	return true;
}

void
memory_region::unmap()
{
	if (pointer == MAP_FAILED)
		return;

	(void)::munmap(pointer, length);

	pointer = MAP_FAILED;
	length = 0;
}

void *
memory_region::get_pointer()
{
	if (pointer == MAP_FAILED)
		return NULL;
	return pointer;
}


text:
package j2html.tags.attributes;

import j2html.tags.IInstance;
import j2html.tags.Tag;

public interface IDefer<T extends Tag<T>> extends IInstance<T> {
    default T isDefer() {
        self().attr("defer");
        return self();
    }

    default T withCondDefer(final boolean enable) {
        if (enable) {
            self().attr("defer");
        }
        return self();
    }
}

redpajama_set_name: RedPajamaGithub


text:
import json
import pytest
import shakedown
import time

import sdk_cmd as cmd
import sdk_install as install
import sdk_tasks as tasks

from tests.config import (
    PACKAGE_NAME,
    DEFAULT_TASK_COUNT,
    check_running
)

def setup_module():
    install.uninstall(PACKAGE_NAME)
    install.install(PACKAGE_NAME, DEFAULT_TASK_COUNT)

def teardown_module(module):
    install.uninstall(PACKAGE_NAME)

@pytest.mark.sanity
@pytest.mark.recovery
def test_kill_hello_node():
    hello_ids = tasks.get_task_ids(PACKAGE_NAME, 'hello-0')
    tasks.kill_task_with_pattern('hello', 'hello-0-server.hello-world.mesos')
    tasks.check_tasks_updated(PACKAGE_NAME, 'hello', hello_ids)

    check_running()

@pytest.mark.sanity
@pytest.mark.recovery
def test_pods_restart():
    hello_ids = tasks.get_task_ids(PACKAGE_NAME, 'hello-0')

    # get current agent id:
    stdout = cmd.run_cli('hello-world pods info hello-0')
    old_agent = json.loads(stdout)[0]['info']['slaveId']['value']

    stdout = cmd.run_cli('hello-world pods restart hello-0')
    jsonobj = json.loads(stdout)
    assert len(jsonobj) == 2
    assert jsonobj['pod'] == 'hello-0'
    assert len(jsonobj['tasks']) == 1
    assert jsonobj['tasks'][0] == 'hello-0-server'

    tasks.check_tasks_updated(PACKAGE_NAME, 'hello', hello_ids)
    check_running()

    # check agent didn't move:
    stdout = cmd.run_cli('hello-world pods info hello-0')
    new_agent = json.loads(stdout)[0]['info']['slaveId']['value']
    assert old_agent == new_agent

@pytest.mark.sanity
@pytest.mark.recovery
def test_pods_replace():
    world_ids = tasks.get_task_ids(PACKAGE_NAME, 'world-0')

    # get current agent id:
    stdout = cmd.run_cli('hello-world pods info world-0')
    old_agent = json.loads(stdout)[0]['info']['slaveId']['value']

    jsonobj = json.loads(cmd.run_cli('hello-world pods replace world-0'))
    assert len(jsonobj) == 2
    assert jsonobj['pod'] == 'world-0'
    assert len(jsonobj['tasks']) == 1
    assert jsonobj['tasks'][0] == 'world-0-server'

    tasks.check_tasks_updated(PACKAGE_NAME, 'world-0', world_ids)
    check_running()

    # check agent moved:
    stdout = cmd.run_cli('hello-world pods info world-0')
    new_agent = json.loads(stdout)[0]['info']['slaveId']['value']
    # TODO: enable assert if/when agent is guaranteed to change (may randomly move back to old agent)
    #assert old_agent != new_agent


text:
package com.arenas.droidfan.data;

/**
 * Created by Arenas on 2016/7/18.
 */
public class StatusColumns {
    public static String TEXT = "text";
    public static String SIMPLE_TEXT = "simple_text";
    public static String SOURCE = "source";
    public static String RAWID = "rawid";// rawid in number format
    public static String ACCOUNT = "account"; // related account id/userid
    public static String OWNER = "owner"; // owner id of the item

    public static String _ID = "_id"; //
    public static String ID = "id"; //

    public static String TIME = "time"; // created at of the item
    public static final String GEO = "geo";

    public static final String USER_ID = "user_id";
    public static final String USER_SCREEN_NAME = "user_screen_name";
    public static final String USER_PROFILE_IMAGE_URL = "user_profile_image_url";

    public static final String IN_REPLY_TO_STATUS_ID = "in_reply_to_status_id";
    public static final String IN_REPLY_TO_USER_ID = "in_reply_to_user_id";
    public static final String IN_REPLY_TO_SCREEN_NAME = "in_reply_to_screen_name";

    public static final String RT_STATUS_ID = "rt_status_id";
    public static final String RT_USER_ID = "rt_user_id";
    public static final String RT_USER_SCREEN_NAME = "rt_user_screen_name";

    public static final String PHOTO_IMAGE_URL = "imageurl";
    public static final String PHOTO_THUMB_URL = "thumburl";
    public static final String PHOTO_LARGE_URL = "largeurl";

    public static final String TRUNCATED = "truncated";
    public static final String FAVORITED = "favorited";
    public static final String RETWEETED = "retweeted";
    public static final String SELF = "self";

    public static final String READ = "read";
    public static final String THREAD = "thread";
    public static final String PHOTO = "photo";
    public static final String SPECIAL = "special";

}


text:
package com.aliakseipilko.flightdutytracker.realm.model;

import java.util.Date;

import io.realm.RealmObject;
import io.realm.annotations.PrimaryKey;
import io.realm.annotations.Required;

public class Flight extends RealmObject {

    @PrimaryKey
    private long id;

    //Dep and Arr
    private String departureIATACode;
    private String departureICAOCode;
    private String arrivalIATACode;
    private String arrivalICAOCode;

    //Times
    @Required
    private Date startDutyTime;
    private Date startFlightTime;
    @Required
    private Date endDutyTime;
    private Date endFlightTime;

    private String acType;
    private String flightNumber;

    public long getId() {
        return id;
    }

    public void setId(long id) {
        this.id = id;
    }

    public String getDepartureIATACode() {
        return departureIATACode;
    }

    public void setDepartureIATACode(String departureIATACode) {
        this.departureIATACode = departureIATACode;
    }

    public String getDepartureICAOCode() {
        return departureICAOCode;
    }

    public void setDepartureICAOCode(String departureICAOCode) {
        this.departureICAOCode = departureICAOCode;
    }

    public String getArrivalIATACode() {
        return arrivalIATACode;
    }

    public void setArrivalIATACode(String arrivalIATACode) {
        this.arrivalIATACode = arrivalIATACode;
    }

    public String getArrivalICAOCode() {
        return arrivalICAOCode;
    }

    public void setArrivalICAOCode(String arrivalICAOCode) {
        this.arrivalICAOCode = arrivalICAOCode;
    }

    public Date getStartDutyTime() {
        return startDutyTime;
    }

    public void setStartDutyTime(Date startDutyTime) {
        this.startDutyTime = startDutyTime;
    }

    public Date getStartFlightTime() {
        return startFlightTime;
    }

    public void setStartFlightTime(Date startFlightTime) {
        this.startFlightTime = startFlightTime;
    }

    public Date getEndDutyTime() {
        return endDutyTime;
    }

    public void setEndDutyTime(Date endDutyTime) {
        this.endDutyTime = endDutyTime;
    }

    public Date getEndFlightTime() {
        return endFlightTime;
    }

    public void setEndFlightTime(Date endFlightTime) {
        this.endFlightTime = endFlightTime;
    }

    public String getAcType() {
        return acType;
    }

    public void setAcType(String acType) {
        this.acType = acType;
    }

    public String getFlightNumber() {
        return flightNumber;
    }

    public void setFlightNumber(String flightNumber) {
        this.flightNumber = flightNumber;
    }
}


text:
package ru.job4j.loop;

import org.junit.Test;
import static org.hamcrest.core.Is.is;
import static org.junit.Assert.assertThat;
/**
* PaintTest класс теста рисования пирамиды числа.
* @author romatihsenko
* @since 19.04.2017
* @version 1
*/
public class PaintTest {
/**
* Тест пирамиды.
*/
@Test
    public void whenThreeThenThinks() {
        Paint paint = new Paint();
        String result = paint.piramid(3);
        String expected = String.format("  ^  %s ^^^ %s^^^^^", System.getProperty("line.separator"), System.getProperty("line.separator"));
        assertThat(result, is(expected));
    }
}


text:
package google

import (
	"fmt"
	"testing"

	"github.com/hashicorp/terraform-plugin-sdk/v2/helper/resource"
	"github.com/hashicorp/terraform-plugin-sdk/v2/terraform"
)

func TestAccComputeTargetTcpProxy_update(t *testing.T) {
	t.Parallel()

	target := fmt.Sprintf("ttcp-test-%s", randString(t, 10))
	backend := fmt.Sprintf("ttcp-test-%s", randString(t, 10))
	hc := fmt.Sprintf("ttcp-test-%s", randString(t, 10))

	vcrTest(t, resource.TestCase{
		PreCheck:     func() { testAccPreCheck(t) },
		Providers:    testAccProviders,
		CheckDestroy: testAccCheckComputeTargetTcpProxyDestroyProducer(t),
		Steps: []resource.TestStep{
			{
				Config: testAccComputeTargetTcpProxy_basic1(target, backend, hc),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckComputeTargetTcpProxyExists(
						t, "google_compute_target_tcp_proxy.foobar"),
				),
			},
			{
				Config: testAccComputeTargetTcpProxy_basic2(target, backend, hc),
				Check: resource.ComposeTestCheckFunc(
					testAccCheckComputeTargetTcpProxyExists(
						t, "google_compute_target_tcp_proxy.foobar"),
				),
			},
		},
	})
}

func testAccCheckComputeTargetTcpProxyExists(t *testing.T, n string) resource.TestCheckFunc {
	return func(s *terraform.State) error {
		rs, ok := s.RootModule().Resources[n]
		if !ok {
			return fmt.Errorf("Not found: %s", n)
		}

		if rs.Primary.ID == "" {
			return fmt.Errorf("No ID is set")
		}

		config := googleProviderConfig(t)
		name := rs.Primary.Attributes["name"]

		found, err := config.NewComputeClient(config.userAgent).TargetTcpProxies.Get(
			config.Project, name).Do()
		if err != nil {
			return err
		}

		if found.Name != name {
			return fmt.Errorf("TargetTcpProxy not found")
		}

		return nil
	}
}

func testAccComputeTargetTcpProxy_basic1(target, backend, hc string) string {
	return fmt.Sprintf(`
resource "google_compute_target_tcp_proxy" "foobar" {
  description     = "Resource created for Terraform acceptance testing"
  name            = "%s"
  backend_service = google_compute_backend_service.foobar.self_link
  proxy_header    = "NONE"
}

resource "google_compute_backend_service" "foobar" {
  name          = "%s"
  protocol      = "TCP"
  health_checks = [google_compute_health_check.zero.self_link]
}

resource "google_compute_health_check" "zero" {
  name               = "%s"
  check_interval_sec = 1
  timeout_sec        = 1
  tcp_health_check {
    port = "443"
  }
}
`, target, backend, hc)
}

func testAccComputeTargetTcpProxy_basic2(target, backend, hc string) string {
	return fmt.Sprintf(`
resource "google_compute_target_tcp_proxy" "foobar" {
  description     = "Resource created for Terraform acceptance testing"
  name            = "%s"
  backend_service = google_compute_backend_service.foobar.self_link
  proxy_header    = "PROXY_V1"
}

resource "google_compute_backend_service" "foobar" {
  name          = "%s"
  protocol      = "TCP"
  health_checks = [google_compute_health_check.zero.self_link]
}

resource "google_compute_health_check" "zero" {
  name               = "%s"
  check_interval_sec = 1
  timeout_sec        = 1
  tcp_health_check {
    port = "443"
  }
}
`, target, backend, hc)
}


text:
<?php

use Illuminate\Database\Migrations\Migration;
use Illuminate\Database\Schema\Blueprint;

class CreateEndpointsTable extends Migration
{
    /**
     * Run the migrations.
     *
     * @return void
     */
    public function up()
    {
        Schema::create('endpoints', function(Blueprint $table) {
            $table->increments('id');
            $table->string('name');
            $table->string('endpoint_url');
            $table->boolean('local');
            $table->timestamps();
            $table->softDeletes();
        });
    }

    /**
     * Reverse the migrations.
     *
     * @return void
     */
    public function down()
    {
        Schema::drop('endpoints');
    }
}


text:
1. Read [GIT 101: Introduction to GIT Source Code Manager](http://ec2-52-24-246-231.us-west-2.compute.amazonaws.com/moodle/course/view.php?id=4)
1. Submit the assignment


text:
NumBBO/CoCO Framework in Matlab and Octave (Experimental Part)
==============================================================

Prerequisites
-------------

The simplest way to check the prerequisits is to go directly to [_Getting Started_](#Getting-Started)
below and give it a try. Then act upon failure, as in this case probably one of
the following is lacking:

- Matlab is installed (version >=2008a) and in the path. Alternatively, you can also use the
  open source platform Octave.

- Python is not installed in the right version (>=2.6). We recommend using the Anaconda package
  (https://www.continuum.io) for installing python.

- A C compiler, like `gcc`, which is invoked by `mex`. For details handling non-supported versions,
  in particular when using `gcc` with MATLAB versions before 2015b, please follow
  http://gnumex.sourceforge.net/oldDocumentation/index.html

Getting Started
---------------

See _Getting Started_ [here](../../../README.md#Getting-Started) for the first steps. Then

- Copy (and rename) the folder `code-experiments/build/matlab` to a place (and name)
  of your choice. Modify the [`exampleexperiment.m`](./code-experiments/build/matlab/exampleexperiment.m`)
  file to include the solver of your choice (instead of random
  search in `my_optimizer`).

- Execute the modified file either from a system shell like
  ```
      matlab exampleexperiment_new_name.m
  ```
  or
  ```
      octave exampleexperiment_new_name.m
  ```
  or in the Matlab/Octave shell like
  ```
      >>> example_experiment_new_name
  ```

See [here](../../../README.md#Getting-Started-pp) for the remaining steps to investate the resulting data.

Details and Known Issues
------------------------
- All of the compilation takes place in the `setup.m` file.
- For using gcc with older MATLAB versions than 2015b, please follow
  http://gnumex.sourceforge.net/oldDocumentation/index.html
- In case that the current Matlab wrapper of the Coco code does not work immediatly on
  the Mac OSX operating system, in particular if some parts have been updated lately, we
  suggest to try to add
  ```
  #define char16_t UINT16_T
  ```
  right before the #include "mex.h" lines of the corresponding C files. This holds
  especially for the more complicated example in ../../examples/bbob-biobj-matlab-smsemoa/.
- When running with GNU Octave under Windows, you might experience that the Windows command window is closed on exit
  of Octave. To solve this issue, find the `octave.bat` file in your Octave installation folder and remove the `exit`
  in the last line or change it to `Rem exit`.

Tested Environments
-------------------
We cannot guarantee that the Matlab wrapper works on any combination of operating system
and compiler. However, compilation has been tested successfully under
   - Mac OSX with MATLAB 2012a
   - Windows 7 with MATLAB 2014a and Visual Studio Professional.
   - Windows 10 with MATLAB 2008a and MinGW
   - Windows XP with MATLAB 2008b and MinGW
   - Windows 7 with GNU Octave 4.0.0


text:
@protocol ZHNAlertProtocol <NSObject>

- (void) onClose:(void(^)())closeHandler;

@end

#endif


text:
export interface IProps extends JSX.Props {
  element: HTMLElement
}

// tslint:disable-next-line:no-unsafe-any
export class Editor implements JSX.ElementClass {
  public element: HTMLElement
  constructor(public props: IProps) {
    this.element = props.element
    this.element.classList.add('ide-haskell-repl')
  }

  public async update(props: IProps) {
    this.element = props.element
    this.element.classList.add('ide-haskell-repl')
    return Promise.resolve()
  }
}


text:
package auth

import (
	"github.com/gorilla/securecookie"
	"net/http"
)

const USER_COOKIE_NAME = "rywww"

var SecureCookie *securecookie.SecureCookie

func initCookie(secret string) {
	var hashKey = []byte(secret)
	var blockKey = []byte(nil)
	SecureCookie = securecookie.New(hashKey, blockKey)
}

func Me(r *http.Request) (int64, string) {
	userid, username := ReadUser(r)
	if userid <= 0 {
		return 0, "not login"
	}

	return userid, username
}

func ReadUser(r *http.Request) (int64, string) {
	if cookie, err := r.Cookie(USER_COOKIE_NAME); err == nil {
		var value CookieData
		if err = SecureCookie.Decode(USER_COOKIE_NAME, cookie.Value, &value); err == nil {
			return value.UserId, value.Username
		}
	}

	return 0, ""
}


text:
import data

class Plant:
	Properties = {}

	def __init__(self, name=""):
		self.name = name

	def Name(self):
		if "Name" in self.Properties.keys():
			return self.Properties["Name"].Value()

	def addProperty(self, attribute, property):
		self.Properties[attribute] = property

def AddPlant(Plant):
	key = Plant.Name()

	return SavePlant(key, Plant)

def SavePlant(key, Plant):
	properties = {}

	for attribute, property in Plant.Properties.items():
		properties[attribute] = property.ToJSON()

	setResult = data.Set(data.Key() + key, {"Properties": properties})

	if setResult == False:
		# throw error
		print("Could not set the key (%s) to the datastore" % (Key() + key))

def GetPlant(key):
	data = data.Get(key)

	Plant = Plant()

	for attribute, property in data["Properties"].items():
		Plant.addProperty(attribute, property.data)

	return Plant


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;

namespace SalesClient.Models
{
    public class ViewDiscovery
    {
        public string Capability { get; set; }
        public string EndpointUri { get; set; }
        public string ResourceId { get; set; }
        public string Version { get; set; }
    }
}


text:
package com.ragstorooks.blacktomove.chess.moves;

import com.ragstorooks.blacktomove.chess.blocks.Colour;
import com.ragstorooks.blacktomove.chess.pieces.Piece;
import com.ragstorooks.blacktomove.chess.pieces.PieceType;
import com.ragstorooks.blacktomove.chess.pieces.Queen;
import com.ragstorooks.blacktomove.chess.pieces.Rook;
import com.ragstorooks.blacktomove.chess.pieces.Bishop;
import com.ragstorooks.blacktomove.chess.pieces.Knight;
import org.apache.commons.lang.builder.ToStringBuilder;

import java.util.Map;

public class Promotion extends BasicMove {
    private PieceType promotionType;

    public Promotion(Colour mover, PieceType promotionType, String destination, boolean isCapture, String sourceHint) {
        super(mover, PieceType.PAWN, destination, isCapture, sourceHint);

        this.promotionType = promotionType;
    }

    @Override
    public EnPassantableEvent move(Map.Entry<String, Piece> source, PieceMover pieceMover) {
        pieceMover.move(source.getKey(), null);
        pieceMover.move(getDestination(), createPromotionPiece(promotionType, source.getValue().getColour()));

        return null;
    }

    private Piece createPromotionPiece(PieceType promotionType, Colour pieceColour) {
        switch (promotionType) {
            case ROOK:
                return new Rook(pieceColour);
            case KNIGHT:
                return new Knight(pieceColour);
            case BISHOP:
                return new Bishop(pieceColour);
            case QUEEN:
                return new Queen(pieceColour);
            default:
                throw new IllegalArgumentException("Unknown promotion piece type: " + promotionType);
        }
    }

    @Override
    public boolean equals(Object o) {
        if (this == o) return true;
        if (o == null || getClass() != o.getClass()) return false;
        if (!super.equals(o)) return false;

        Promotion promotion = (Promotion) o;

        if (promotionType != promotion.promotionType) return false;

        return true;
    }

    @Override
    public int hashCode() {
        int result = super.hashCode();
        result = 31 * result + (promotionType != null ? promotionType.hashCode() : 0);
        return result;
    }

    @Override
    public String toString() {
        return new ToStringBuilder(this).appendSuper(super.toString()).append("promotionType", promotionType)
                .toString();
    }
}


text:
package com.datatorrent.lib.bucket;

import javax.annotation.Nonnull;

/**
 * Test event.
 */
public class DummyEvent implements Event, Bucketable, Comparable<DummyEvent>
{
  Integer id;
  long time;

  @SuppressWarnings("unused")
  DummyEvent()
  {
  }

  public DummyEvent(int id, long time)
  {
    this.id = id;
    this.time = time;
  }

  @Override
  public long getTime()
  {
    return time;
  }

  @Override
  public boolean equals(Object o)
  {
    if (this == o) {
      return true;
    }
    if (!(o instanceof DummyEvent)) {
      return false;
    }

    DummyEvent that = (DummyEvent)o;

    if (time != that.time) {
      return false;
    }
    if (id != null ? !id.equals(that.id) : that.id != null) {
      return false;
    }

    return true;
  }

  @Override
  public int hashCode()
  {
    int result = id != null ? id.hashCode() : 0;
    result = 31 * result + (int)(time ^ (time >>> 32));
    return result;
  }

  @Override
  public Object getEventKey()
  {
    return id;
  }

  @Override
  public int compareTo(@Nonnull DummyEvent dummyEvent)
  {
    return id - dummyEvent.id;
//    if (this.equals(dummyEvent)) {
//      return 0;
//    }
//    if (id < dummyEvent.id) {
//      return -1;
//    }
//    return 1;
  }

  @Override
  public String toString()
  {
    return "{id=" + id + ", time=" + time + '}';
  }
}


text:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Xna.Framework;

namespace ReleaseTest
{
    public class TesterLabels : Tester
    {
        float elapsed;

        public Vector3 TestVector3;

        public TesterLabels(Game game)
            : base(game)
        {
            TestVector3 = new Vector3(0, 4, 5);
        }

        public override void Initialize()
        {
            base.Initialize();
        }

        public override void Update(GameTime gameTime)
        {
            float dt = (float)gameTime.ElapsedGameTime.TotalSeconds;
            elapsed += dt;

            Vector3 position3 = new Vector3((float)Math.Sin(elapsed), (float)Math.Cos(elapsed), 0);

            Debug.GS.ShowLabel("Label3D_NoText", position3);

            position3 += Vector3.UnitX * 2;
            Debug.GS.ShowLabel("Label3DT", position3, "Label3D_WithText");

            position3 += Vector3.UnitX * 2;
            Debug.GS.ShowLabel("Label3DTC", position3, "Label3D_WithTextColor", Color.Orange);

            Vector2 position2 = new Vector2(100 + (float)Math.Sin(elapsed) * 80, 100 + (float)Math.Cos(elapsed) * 80);

            Debug.GS.ShowLabel("Label2D_NoText", position2);

            position2 += Vector2.UnitX * 200;
            Debug.GS.ShowLabel("Label2DT", position2, "Label2D_WithText");

            position2 += Vector2.UnitX * 200;
            Debug.GS.ShowLabel("Label2DTC", position2, "Label2D_WithTextColor", Color.Red);

            base.Update(gameTime);
        }

        public override void Draw(GameTime gameTime)
        {
            base.Draw(gameTime);
        }
    }
}


text:
package org.azeckoski.reflectutils.classes;

import org.azeckoski.reflectutils.ClassFields.FieldsFilter;

/**
 * Class that is made to test {@link FieldsFilter}

 * {@link FieldsFilter#ALL}: {@link #field},{@link #fin},{@link #property},{@link #read},{@link #trans},{@link #write}

 * {@link FieldsFilter#COMPLETE}: {@link #field},{@link #property},{@link #trans}

 * {@link FieldsFilter#READABLE}: {@link #field},{@link #fin},{@link #property},{@link #read},{@link #trans}

 * {@link FieldsFilter#SERIALIZABLE}: {@link #field},{@link #fin},{@link #property},{@link #read}

 * {@link FieldsFilter#WRITEABLE}: {@link #field},{@link #property},{@link #trans},{@link #write}

 *
 * @author Aaron Zeckoski (azeckoski @ gmail.com)
 */
@SuppressWarnings("unused")
public class TestFilter {

    public String field = "field";
    public transient String trans = "transient";
    public final String fin = "final";

    private String read = null;
    private String write = null;
    private String property = "property";
    private String unused = "unused";

    public String getRead() {
        return read;
    }

    public void setWrite(String write) {
        this.write = write;
    }

    public void setProperty(String property) {
        this.property = property;
    }
    public String getProperty() {
        return property;
    }

}


text:
/* ###
 * IP: GHIDRA
 *
 * 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 agent.dbgmodel.gadp.impl;

import java.nio.ByteBuffer;
import java.util.*;

import com.sun.jna.platform.win32.WinDef.ULONGLONG;
import com.sun.jna.platform.win32.COM.COMException;

import agent.dbgeng.dbgeng.*;
import agent.dbgeng.dbgeng.DebugRunningProcess.Description;
import agent.dbgeng.dbgeng.DebugRunningProcess.Description.ProcessDescriptionFlags;
import agent.dbgeng.dbgeng.DebugValue.*;
import agent.dbgmodel.dbgmodel.bridge.HostDataModelAccess;
import agent.dbgmodel.dbgmodel.debughost.*;
import agent.dbgmodel.dbgmodel.main.ModelObject;
import agent.dbgmodel.impl.dbgmodel.DebugRunningProcessImpl;
import agent.dbgmodel.impl.dbgmodel.bridge.HDMAUtil;
import agent.dbgmodel.jna.dbgmodel.DbgModelNative.LOCATION;
import ghidra.comm.util.BitmaskSet;

public class WrappedDbgModel
		implements DebugClient, DebugSystemObjects, DebugRegisters, DebugDataSpaces, DebugSymbols {

	private HDMAUtil util;
	private DebugClient client;
	private HashMap<Object, String> map = new HashMap<Object, String>();
	private boolean USE_CLIENT = false;

	//private boolean USE_CLIENT = true;

	public WrappedDbgModel(HostDataModelAccess access) {
		util = new HDMAUtil(access);
		client = access.getClient();
		System.err.println(">>>>>>>>>>>>  USING WRAPPED DBGMODEL  <<<<<<<<<<<<<<");
	}

	public DebugClient getClient() {
		return this;
	}

	// Used to get ExitTime/Status for threads
	@Override
	public DebugAdvanced getAdvanced() {
		return client.getAdvanced();
	}

	// Used for control, I/O, breakpoints
	@Override
	public DebugControl getControl() {
		return client.getControl();
	}

	// Used to enumerate/read-write regions
	@Override
	public DebugDataSpaces getDataSpaces() {
		return this;
	}

	// Used to enumerate registers
	@Override
	public DebugRegisters getRegisters() {
		return this;
	}

	// Used to enumerate threads/processes
	@Override
	public DebugSystemObjects getSystemObjects() {
		return this;
	}

	// Used to enumerate symbols
	@Override
	public DebugSymbols getSymbols() {
		return this;
	}

	public Map<String, ModelObject> getAttributes(List<String> path) {
		return getUtil().getAttributes(path);
	}

	public List<ModelObject> getElements(List<String> path) {
		return getUtil().getElements(path);
	}

	public ModelObject getMethod(List<String> path) {
		return getUtil().getMethod(path);
	}

	@Override
	public void attachProcess(DebugServerId si, long processId,
			BitmaskSet<DebugAttachFlags> attachFlags) {
		client.attachProcess(si, processId, attachFlags);
	}

	@Override
	public void createProcess(DebugServerId si, String commandLine,
			String initialDirectory, String environment,
			BitmaskSet<DebugCreateFlags> createFlags,
			BitmaskSet<DebugEngCreateFlags> engCreateFlags,
			BitmaskSet<DebugVerifierFlags> verifierFlags) {
		client.createProcess(si, commandLine,
			initialDirectory, environment,
			createFlags, engCreateFlags, verifierFlags);
	}

	@Override
	public void createProcessAndAttach(DebugServerId si, String commandLine,
			BitmaskSet<DebugCreateFlags> createFlags, int processId,
			BitmaskSet<DebugAttachFlags> attachFlags) {
		client.createProcessAndAttach(si, commandLine, createFlags, processId, attachFlags);
	}

	@Override
	public void abandonCurrentProcess() {
		client.abandonCurrentProcess();
	}

	@Override
	public void startServer(String options) {
		client.startServer(options);
	}

	@Override
	public void waitForProcessServerEnd(int timeout) {
		client.waitForProcessServerEnd(timeout);
	}

	@Override
	public void terminateCurrentProcess() {
		client.terminateCurrentProcess();
	}

	@Override
	public void detachCurrentProcess() {
		client.detachCurrentProcess();
	}

	@Override
	public void connectSession(int flags) {
		client.connectSession(flags);
	}

	@Override
	public void endSession(DebugEndSessionFlags flags) {
		client.endSession(flags);
	}

	public HDMAUtil getUtil() {
		return util;
	}

	@Override
	public DebugClient createClient() {
		return client;
	}

	@Override
	public void endSessionReentrant() {
		client.endSessionReentrant();
	}

	@Override
	public DebugServerId getLocalServer() {
		return client.getLocalServer();
	}

	@Override
	public void attachKernel(long flags, String options) {
		client.attachKernel(flags, options);
	}

	@Override
	public void startProcessServer(String options) {
		client.startProcessServer(options);
	}

	@Override
	public DebugServerId connectProcessServer(String options) {
		return client.connectProcessServer(options);
	}

	@Override
	public boolean dispatchCallbacks(int timeout) {
		return client.dispatchCallbacks(timeout);
	}

	@Override
	public void flushCallbacks() {
		client.flushCallbacks();
	}

	@Override
	public void exitDispatch(DebugClient client) {
		client.exitDispatch(client);
	}

	@Override
	public void setInputCallbacks(DebugInputCallbacks cb) {
		client.setInputCallbacks(cb);
	}

	@Override
	public void setOutputCallbacks(DebugOutputCallbacks cb) {
		client.setOutputCallbacks(cb);
	}

	@Override
	public void setEventCallbacks(DebugEventCallbacks cb) {
		client.setEventCallbacks(cb);
	}

	@Override
	public Description getProcessDescription(DebugServerId si, int systemId,
			BitmaskSet<ProcessDescriptionFlags> flags) {
		return client.getProcessDescription(si, systemId, flags);
	}

	@Override
	public void openDumpFileWide(String fileName) {
		client.openDumpFileWide(fileName);
	}

	// DATA SPACES INTERFACE

	@Override
	public int readVirtual(long offset, ByteBuffer buf, int remaining) {
		DebugHostContext currentContext = getUtil().getCurrentContext();
		DebugHost host = getUtil().getHost();
		ULONGLONG ulOffset = new ULONGLONG(offset);
		LOCATION base = new LOCATION(ulOffset);
		DebugHostMemory1 memory = host.asMemory();
		return (int) memory.readBytes(currentContext, base, buf, remaining);
	}

	@Override
	public int writeVirtual(long offset, ByteBuffer buf, int remaining) {
		// UNTESTED
		DebugHostContext currentContext = getUtil().getCurrentContext();
		DebugHost host = getUtil().getHost();
		ULONGLONG ulOffset = new ULONGLONG(offset);
		LOCATION base = new LOCATION(ulOffset);
		DebugHostMemory1 memory = host.asMemory();
		return (int) memory.writeBytes(currentContext, base, buf, remaining);
	}

	@Override
	public int readVirtualUncached(long offset, ByteBuffer into, int len) {
		return readVirtual(offset, into, len);
	}

	@Override
	public int writeVirtualUncached(long offset, ByteBuffer from, int len) {
		return readVirtual(offset, from, len);
	}

	// TODO what follows is untested

	@Override
	public int readPhysical(long offset, ByteBuffer buf, int remaining) {
		return client.getDataSpaces().readPhysical(offset, buf, remaining);
	}

	@Override
	public int writePhysical(long offset, ByteBuffer buf, int remaining) {
		return client.getDataSpaces().writePhysical(offset, buf, remaining);
	}

	@Override
	public int readControl(int processor, long offset, ByteBuffer buf, int remaining) {
		return client.getDataSpaces().readControl(processor, offset, buf, remaining);
	}

	@Override
	public int writeControl(int processor, long offset, ByteBuffer buf, int remaining) {
		return client.getDataSpaces().writeControl(processor, offset, buf, remaining);
	}

	@Override
	public int readBusData(int busDataType, int busNumber, int slotNumber, long offset,
			ByteBuffer buf, int remaining) {
		return client.getDataSpaces()
				.readBusData(busDataType, busNumber, slotNumber, offset, buf, remaining);
	}

	@Override
	public int writeBusData(int busDataType, int busNumber, int slotNumber, long offset,
			ByteBuffer buf, int remaining) {
		return client.getDataSpaces()
				.writeBusData(busDataType, busNumber, slotNumber, offset, buf, remaining);
	}

	@Override
	public int readIo(int interfaceType, int busNumber, int addressSpace, long offset,
			ByteBuffer buf, int remaining) {
		return client.getDataSpaces()
				.readIo(interfaceType, busNumber, addressSpace, offset, buf, remaining);
	}

	@Override
	public int writeIo(int interfaceType, int busNumber, int addressSpace, long offset,
			ByteBuffer buf, int remaining) {
		return client.getDataSpaces()
				.writeIo(interfaceType, busNumber, addressSpace, offset, buf, remaining);
	}

	@Override
	public long readMsr(int msr) {
		return client.getDataSpaces().readMsr(msr);
	}

	@Override
	public void writeMsr(int msr, long value) {
		client.getDataSpaces().writeMsr(msr, value);
	}

	@Override
	public int readDebuggerData(int offset, ByteBuffer buf, int remaining) {
		DebugHostContext currentContext = getUtil().getCurrentContext();
		DebugHost host = getUtil().getHost();
		ULONGLONG ulOffset = new ULONGLONG(offset);
		LOCATION base = new LOCATION(ulOffset);
		DebugHostMemory1 memory = host.asMemory();
		return (int) memory.readBytes(currentContext, base, buf, remaining);
	}

	@Override
	public DebugMemoryBasicInformation queryVirtual(long offset) {
		return client.getDataSpaces().queryVirtual(offset);
	}

	@Override
	public long virtualToPhysical(long offset) {
		return client.getDataSpaces().virtualToPhysical(offset);
	}

	// REGISTERS INTERFACE

	public DebugRegisterDescription getRegisterDescription(int i) {
		return client.getRegisters().getDescription(i);
		/*
		if (USE_CLIENT) {
			System.err.println("getRegisterDescription");
			return client.getRegisters().getDescription(i);
		}
		*/
		/*
		Map<String, ModelObject> registerMap = getRegisterMap();
		Object[] array = registerMap.keySet().toArray();
		if (i > array.length) {
			DebugRegisterDescription description = client.getRegisters().getDescription(i);
			System.err.println(description.name + " not found");
			return null;
		}
		String regname = (String) array[i];
		ModelObject register = registerMap.get(regname);
		DebugRegisterDescription drp = new DebugRegisterDescription(regname, i, getDVType(register),
			new BitmaskSet<>(DebugRegisterFlags.class, 0), 0, 0, 0, 0);
		return drp;
		*/
	}

	public Set<DebugRegisterDescription> getAllRegisterDescriptions() {
		return client.getRegisters().getAllDescriptions();
		/*
		if (USE_CLIENT) {
			System.err.println("getAllRegisterDescriptions");
			return client.getRegisters().getAllDescriptions();
		}
		*/
		/*
		Set<DebugRegisterDescription> set = new HashSet<DebugRegisters.DebugRegisterDescription>();
		Map<String, ModelObject> registerMap = getRegisterMap();
		Object[] array = registerMap.keySet().toArray();
		for (int i = 0; i < array.length; i++) {
			String regname = (String) array[i];
			if (regname == null) {
				continue;
			}
			ModelObject register = registerMap.get(regname);
			DebugRegisterDescription drp = new DebugRegisterDescription(regname, i,
				getDVType(register), new BitmaskSet<>(DebugRegisterFlags.class, 0), 0, 0, 0, 0);
			set.add(drp);
		}
		return set;
		*/
	}

	/*
	public void setRegisterValue(Entry<String, byte[]> ent) {
		System.err.println("setRegisterValue");
		Map<String, ModelObject> registerMap = getRegisterMap();
		ModelObject register = registerMap.get(ent.getKey());
		DebugValue value = decodeBytes(register, ent.getValue());
		client.getRegisters().setValueByName(ent.getKey(), value);
	}
	*/

	@Override
	public int getNumberRegisters() {
		return client.getRegisters().getNumberRegisters();
		//return getRegisterMap().size();
	}

	@Override
	public DebugRegisterDescription getDescription(int registerNumber) {
		return getRegisterDescription(registerNumber);
	}

	@Override
	public int getIndexByName(String name) {
		return client.getRegisters().getIndexByName(name);
		/*
		if (USE_CLIENT) {
			System.err.println("getAllRegisterDescriptions");
			return client.getRegisters().getIndexByName(name);
		}
		*/
		/*
		TreeMap<String, ModelObject> registerMap = (TreeMap) getRegisterMap();
		Object[] array = registerMap.keySet().toArray();
		for (int i = 0; i < array.length; i++) {
			String key = (String) array[i];
			if (key.equals(name)) {
				return i;
			}
		}
		return -1;
		*/
	}

	@Override
	public DebugValue getValueByName(String name) {
		return client.getRegisters().getValueByName(name);
		//TreeMap<String, ModelObject> registerMap = (TreeMap) getRegisterMap();
		//ModelObject obj = registerMap.get(name);
		//return getDebugValue(obj);
	}

	@Override
	public DebugValue getValue(int index) {
		return client.getRegisters().getValue(index);
		/*
		if (USE_CLIENT) {
			System.err.println("getAllRegisterDescriptions");
			return client.getRegisters().getValue(index);
		}
		*/
		/*
		TreeMap<String, ModelObject> registerMap = (TreeMap) getRegisterMap();
		Object[] array = registerMap.values().toArray();
		if (index >= 0 && index < array.length) {
			ModelObject obj = (ModelObject) array[index];
			return getDebugValue(obj);
		}
		return null;
		*/
	}

	@Override
	public Map<Integer, DebugValue> getValues(DebugRegisterSource source,
			Collection<Integer> indices) {
		return client.getRegisters().getValues(source, indices);
		/*
		if (USE_CLIENT) {
			System.err.println("getAllRegisterDescriptions");
			return client.getRegisters().getValues(source, indices);
		}
		*/
		/*
		TreeMap<String, ModelObject> registerMap = (TreeMap) getRegisterMap();
		Object[] array = registerMap.keySet().toArray();
		Map<Integer, DebugValue> registers = new TreeMap<Integer, DebugValue>();
		for (Integer index : indices) {
			String key = (String) array[index];
			ModelObject obj = registerMap.get(key);
			registers.put(index, getDebugValue(obj));
		}
		return registers;
		*/
	}

	@Override
	public void setValueByName(String name, DebugValue value) {
		setValue(getIndexByName(name), value);
	}

	@Override
	public void setValue(int index, DebugValue value) {
		client.getRegisters().setValue(index, value);
	}

	@Override
	public void setValues(DebugRegisterSource source, Map<Integer, DebugValue> values) {
		client.getRegisters().setValues(source, values);
	}

	// SYSTEM OBJECT INTERFACE

	public List<DebugThreadId> getThreadIds() {
		List<DebugThreadId> ids = null;
		/*
		if (USE_CLIENT) {
			System.err.println("getThreadIds");
			ids = client.getSystemObjects().getThreads();
			return ids;
		}
		*/
		ModelObject currentSession = getUtil().getCurrentSession();
		ModelObject currentProcess = getUtil().getCurrentProcess();
		String pid = getUtil().getCtlId(currentProcess);
		List<ModelObject> runningThreads = getUtil().getRunningThreads(currentSession, pid);
		ids = new ArrayList<DebugThreadId>();
		for (ModelObject t : runningThreads) {
			String tid = getUtil().getCtlId(t);
			ids.add(tid2dti(tid));
		}
		return ids;
	}

	public List<DebugProcessId> getProcessIds() {
		/*
		if (USE_CLIENT) {
			System.err.println("getProcessIds");
			return client.getSystemObjects().getProcesses();
		}
		*/
		// TODO: What follow is problematic.  SO.getProcesses uses SO.GetNumberProcesses
		// and GetProcessIdsByIndex, which return the processes being debugged, not the
		// system process list. Using the system process list and calling getProcessIdBySystemID
		// triggers unsupported interface COM exceptions
		List<DebugProcessId> ids = new ArrayList<DebugProcessId>();
		List<DebugRunningProcess> procs = getRunningProcesses(sid2dsi());
		for (DebugRunningProcess p : procs) {
			try {
				ids.add(pid2dpi("0x" + Integer.toHexString(p.getSystemId())));
			}
			catch (COMException e) {
				System.err.println(p.getSystemId());
			}
		}
		return ids;
	}

	@Override
	public void setCurrentSystemId(DebugSessionId dpi) {
		client.getSystemObjects().setCurrentSystemId(dpi);
		/*
		if (USE_CLIENT) {
			System.err.println("setCurrentProcess");
			client.getSystemObjects().setCurrentProcessId(dpi);
			return;
		}
		*//* DOESN'T WORK
			String pid = obj2id(dpi);
			ModelObject currentProcess = util.getCurrentProcess();
			util.setCurrentProcess(currentProcess, pid);
			*/
	}

	@Override
	public void setCurrentProcessId(DebugProcessId dpi) {
		client.getSystemObjects().setCurrentProcessId(dpi);
		/*
		if (USE_CLIENT) {
			System.err.println("setCurrentProcess");
			client.getSystemObjects().setCurrentProcessId(dpi);
			return;
		}
		*//* DOESN'T WORK
			String pid = obj2id(dpi);
			ModelObject currentProcess = util.getCurrentProcess();
			util.setCurrentProcess(currentProcess, pid);
			*/
	}

	@Override
	public void setCurrentThreadId(DebugThreadId dti) {
		DebugSystemObjects so = client.getSystemObjects();
		DebugThreadId currentThreadId = so.getCurrentThreadId();
		if (dti.id != currentThreadId.id) {
			so.setCurrentThreadId(dti);
		}
		/*
		if (USE_CLIENT) {
			System.err.println("setCurrentThread");
			client.getSystemObjects().setCurrentThreadId(dti);
			return;
		}
		*//* DOESN'T WORK
			String tid = obj2id(dti);
			ModelObject currentThread = util.getCurrentThread();
			util.setCurrentThread(currentThread, tid);
			*/
	}

	@Override
	public DebugSessionId getCurrentSystemId() {
		/*
		if (USE_CLIENT) {
			System.err.println("getCurrentSystemId");
			return client.getSystemObjects().getCurrentSystemId();
		}
		*/
		return client.getSystemObjects().getCurrentSystemId();
	}

	@Override
	public DebugProcessId getCurrentProcessId() {
		/*
		if (USE_CLIENT) {
			System.err.println("getCurrentProcessId");
			return client.getSystemObjects().getCurrentProcessId();
		}
		*/
		ModelObject currentProcess = getUtil().getCurrentProcess();
		DebugProcessId dpi = client.getSystemObjects().getCurrentProcessId();
		if (currentProcess != null) {
			String id = getUtil().getCtlId(currentProcess);
			addObj(dpi, id);
		}
		return dpi;
	}

	@Override
	public DebugThreadId getCurrentThreadId() {
		/*
		if (USE_CLIENT) {
			System.err.println("getCurrentThreadId");
			return client.getSystemObjects().getCurrentThreadId();
		}
		*/
		ModelObject currentThread = getUtil().getCurrentThread();
		DebugThreadId dti = client.getSystemObjects().getCurrentThreadId();
		if (currentThread != null) {
			String id = getUtil().getCtlId(currentThread);
			addObj(dti, id);
		}
		return dti;
	}

	@Override
	public DebugProcessId getProcessIdByHandle(long handle) {
		// "Handle" key exists for processes, but not threads currently
		return client.getSystemObjects().getProcessIdByHandle(handle);
	}

	@Override
	public DebugThreadId getThreadIdByHandle(long handle) {
		// "Handle" key exists for processes, but not threads currently
		return client.getSystemObjects().getThreadIdByHandle(handle);
	}

	@Override
	public DebugSessionId getEventSystem() {
		/*
		if (USE_CLIENT) {
			System.err.println("getEventProcess");
			return client.getSystemObjects().getEventProcess();
		}
		*/
		return client.getSystemObjects().getEventSystem();
		//return getCurrentProcessId();
	}

	@Override
	public DebugProcessId getEventProcess() {
		/*
		if (USE_CLIENT) {
			System.err.println("getEventProcess");
			return client.getSystemObjects().getEventProcess();
		}
		*/
		return client.getSystemObjects().getEventProcess();
		//return getCurrentProcessId();
	}

	@Override
	public DebugThreadId getEventThread() {
		/*
		if (USE_CLIENT) {
			System.err.println("getEventThread");
			return client.getSystemObjects().getEventThread();
		}
		*/
		return client.getSystemObjects().getEventThread();
		//return getCurrentThreadId();
	}

	@Override
	public List<DebugRunningProcess> getRunningProcesses(DebugServerId si) {
		/*
		if (USE_CLIENT) {
			System.err.println("getRunningProcesses");
			return client.getRunningProcesses(si);
		}
		*/
		List<ModelObject> processes = getUtil().getRunningProcesses(obj2id(si));
		List<DebugRunningProcess> result = new ArrayList<>(processes.size());
		for (ModelObject child : processes) {
			String pid = getUtil().getCtlId(child);
			result.add(new DebugRunningProcessImpl(pid, child, si));
		}
		return result;
	}

	@Override
	public int getCurrentThreadSystemId() {  // used by impl
		return client.getSystemObjects().getCurrentThreadSystemId();
		//return getCurrentThreadId().id;
	}

	@Override
	public int getCurrentProcessSystemId() {  // used by impl
		return client.getSystemObjects().getCurrentProcessSystemId();
		//return getCurrentProcessId().id;
	}

	@Override
	public int getNumberThreads() {  // used by dso
		return client.getSystemObjects().getNumberThreads();
	}

	@Override
	public List<DebugThreadId> getThreads(int start, int count) { // used by dso
		return client.getSystemObjects().getThreads(start, count);
	}

	@Override
	public int getNumberProcesses() {  // used by dso
		return client.getSystemObjects().getNumberProcesses();
	}

	@Override
	public List<DebugProcessId> getProcesses(int start, int count) {  // used by dso
		return client.getSystemObjects().getProcesses(start, count);
	}

	@Override
	public int getNumberSystems() {  // used by dso
		return client.getSystemObjects().getNumberSystems();
	}

	@Override
	public List<DebugSessionId> getSystems(int start, int count) {  // used by dso
		return client.getSystemObjects().getSystems(start, count);
	}

	@Override
	public DebugThreadId getThreadIdBySystemId(int systemId) {  // used by this
		return client.getSystemObjects().getThreadIdBySystemId(systemId);
	}

	@Override
	public DebugProcessId getProcessIdBySystemId(int systemId) {  // used by this
		return client.getSystemObjects().getProcessIdBySystemId(systemId);
	}

	@Override
	public int getTotalNumberThreads() {  // unused
		return client.getSystemObjects().getTotalNumberThreads();
	}

	// SYMBOLS INTERFACE

	public List<DebugHostModule1> getDebugHostModules() {
		DebugHostSymbols symbols = getUtil().getHost().asSymbols();
		DebugHostSymbolEnumerator enumerator =
			symbols.enumerateModules(getUtil().getCurrentContext());
		List<DebugHostModule1> list = new ArrayList<DebugHostModule1>();
		DebugHostSymbol1 next;
		while ((next = enumerator.getNext()) != null) {
			list.add(next.asModule());
		}
		return list;
	}

	public List<DebugModule> getModuleList() {
		return getUtil().getModuleList();
	}

	@Override
	public int getNumberLoadedModules() {
		return getModuleList().size();
	}

	@Override
	public int getNumberUnloadedModules() {
		return client.getSymbols().getNumberUnloadedModules();
	}

	@Override
	public DebugModule getModuleByIndex(int index) {
		List<DebugModule> modules = getModuleList();
		return modules.get(index);
	}

	@Override
	public DebugModule getModuleByModuleName(String name, int startIndex) {
		List<DebugModule> modules = getModuleList();
		for (DebugModule module : modules) {
			String moduleName = module.getName(null);
			if (moduleName.equals(name)) {
				return module;
			}
		}
		System.err.println(name + " not found");
		return null;
	}

	@Override
	public DebugModule getModuleByOffset(long offset, int startIndex) {
		List<DebugModule> modules = getModuleList();
		long min = Long.MAX_VALUE;
		DebugModule ret = null;
		for (DebugModule module : modules) {
			long baseAddress = module.getBase();
			if (offset >= baseAddress && baseAddress < min) {
				min = baseAddress;
				ret = module;
			}
		}
		return ret;
	}

	@Override
	public DebugModuleInfo getModuleParameters(int count, int startIndex) {
		return client.getSymbols().getModuleParameters(count, startIndex);
	}

	@Override
	public Iterable<DebugSymbolName> iterateSymbolMatches(String pattern) {
		return client.getSymbols().iterateSymbolMatches(pattern);
	}

	@Override
	public List<DebugSymbolId> getSymbolIdsByName(String pattern) {
		return client.getSymbols().getSymbolIdsByName(pattern);
	}

	@Override
	public DebugSymbolEntry getSymbolEntry(DebugSymbolId id) {
		return client.getSymbols().getSymbolEntry(id);
	}

	@Override
	public String getSymbolPath() {
		return client.getSymbols().getSymbolPath();
	}

	@Override
	public void setSymbolPath(String path) {
		client.getSymbols().setSymbolPath(path);
	}

	@Override
	public int getSymbolOptions() {
		return client.getSymbols().getSymbolOptions();
	}

	@Override
	public void setSymbolOptions(int options) {
		client.getSymbols().setSymbolOptions(options);
	}

	// UTILITY METHODS

	private DebugServerId sid2dsi() {
		DebugServerId dsi = new DebugServerId(0);
		addObj(dsi, "0");
		return dsi;
	}

	private DebugProcessId pid2dpi(String id) {
		if (!id.startsWith("0x")) {
			id = "0x" + id;
		}
		int pid = Integer.decode(id);
		if (pid == 0) {
			return new DebugProcessId(-1);
		}
		DebugProcessId dpi = client.getSystemObjects().getProcessIdBySystemId(pid);
		addObj(dpi, id);
		return dpi;
	}

	private DebugThreadId tid2dti(String id) {
		if (!id.startsWith("0x")) {
			id = "0x" + id;
		}
		int tid = Integer.decode(id);
		DebugThreadId dti = client.getSystemObjects().getThreadIdBySystemId(tid);
		addObj(dti, id);
		return dti;
	}

	private void addObj(Object obj, String id) {
		if (obj == null || id == null) {
			System.err.println("attempt to add null object");
		}
		map.put(obj, id);
	}

	private String obj2id(Object obj) {
		String id = map.get(obj);
		return id;
	}

	public DebugValue getDebugValue(ModelObject register) {
		DebugValue dv = null;
		Object value = register.getValue();
		if (value instanceof Short) {
			dv = new DebugInt16Value(((Short) value).shortValue());
		}
		else if (value instanceof Integer) {
			dv = new DebugInt32Value(((Integer) value).intValue());
		}
		else if (value instanceof Long) {
			dv = new DebugInt64Value(((Long) value).longValue());
		}
		return dv;
	}

	public byte[] encodeAsBytes(ModelObject register) {
		DebugValue dv = null;
		Object value = register.getValue();
		if (value instanceof Short) {
			Short lval = (Short) value;
			dv = new DebugInt16Value(lval);
		}
		else if (value instanceof Integer) {
			Integer lval = (Integer) value;
			dv = new DebugInt32Value(lval);
		}
		else if (value instanceof Long) {
			Long lval = (Long) value;
			dv = new DebugInt64Value(lval);
		}
		else {
			return new byte[0];
		}
		return dv.encodeAsBytes();
	}

	private DebugValue decodeBytes(ModelObject register, byte[] bytes) {
		DebugValue dv = null;
		Object value = register.getValue();
		if (value instanceof Short) {
			dv = new DebugInt16Value(bytes);
		}
		else if (value instanceof Integer) {
			dv = new DebugInt32Value(bytes);
		}
		else if (value instanceof Long) {
			dv = new DebugInt64Value(bytes);
		}
		return dv;
	}

	private DebugValueType getDVType(ModelObject register) {
		Object value = register.getValue();
		if (value instanceof Short) {
			return DebugValueType.INT16;
		}
		else if (value instanceof Integer) {
			return DebugValueType.INT32;
		}
		else if (value instanceof Long) {
			return DebugValueType.INT64;
		}
		return DebugValueType.INVALID;
	}

	@Override
	public int getCurrentScopeFrameIndex() {
		return client.getSymbols().getCurrentScopeFrameIndex();
	}

	@Override
	public void setCurrentScopeFrameIndex(int index) {
		client.getSymbols().setCurrentScopeFrameIndex(index);
	}

}


text:
from path import path
import os
import pickle
"""
A class providing dictionary access to a folder.
cribbed from http://bitbucket.org/howthebodyworks/fsdict
"""

def get_tmp_dir():
    import tempfile
    return tempfile.mkdtemp()

class FSDict(dict):
    """
    provide dictionary access to a temp dir. I don't know why i didn't just use
    shelve. I think I forgot it existed.

    N.B. the keys ordering here is FS-dependent and thus unlike to be the same as
    with a real dict. beware.
    """

    unclean_dirs = []

    def __init__(self, initval=[], work_dir=None, *args, **kwargs):
        if work_dir is None:
            work_dir = get_tmp_dir()
        self.work_dir = path(work_dir)
        if not self.work_dir.exists():
            self.work_dir.mkdir()
        for key, val in getattr(initval, 'iteritems', initval.__iter__)():
            self[key] = val
        self.unclean_dirs.append(self.work_dir)
        super(FSDict, self).__init__(*args, **kwargs)

    def __setitem__(self, key, val, *args, **kwargs):
        pickle.dump(val, open(self.work_dir/key, 'w'))

    def __getitem__(self, key, *args, **kwargs):
        return pickle.load(open(self.work_dir/key, 'r'))

    def __repr__(self):
        """
        a hardline list of everything in the dict. may be long.
        """
        return repr(dict([(k, v) for k, v in self.iteritems()]))

    def __str__(self):
        """
        str is truncated somewhat.
        """
        if len(self.keys()):
            return '{' + repr(self.keys()[0]) + ':' + repr(self[self.keys()[0]]) + ', ...'
        else:
            return super(FSDict, self).__str__()

    def keys(self, *args, **kwargs):
        return [key for key in self.iterkeys()]

    def iterkeys(self, *args, **kwargs):
        for f in self.work_dir.files():
            yield str(self.work_dir.relpathto(f))

    def iteritems(self):
        for key in self.iterkeys():
            yield key, self[key]

    def itervalues(self):
        for key in self.iterkeys():
            yield self[key]

    def __delitem__(self, key, *args, **kwargs):
        (self.work_dir/key).unlink()

    def values(self, *args, **kwargs):
        return [self[key] for key in self.keys()]

    def cleanup(self):
        self.work_dir.rmtree()

    @classmethod
    def cleanup_all(cls):
        for fsd in cls.unclean_dirs:
            try:
                fsd.rmtree()
            except OSError:
                pass

    def move(self, new_dir):

        try:
            self.work_dir.move(new_dir)
        except Exception, e:
            raise
        else:
            self.work_dir = new_dir

    def __eq__(self, other):
        """
        when compared to a dict, equate equal if all keys and vals are equal
        note, this is potentially expensive.
        """
        #duck type our way to sanity:
        if not hasattr(other, 'keys'): return False
        #OK, it's a dict-ish thing
        try:
            return all([self[key]==other[key] for key in other]) and \
              len(self.keys())==len(other.keys())
        except KeyError:
            return False


text:
package org.wso2.carbon.apimgt.rest.api.core.impl;

import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
import org.wso2.carbon.apimgt.core.impl.APIManagerFactory;
import org.wso2.carbon.apimgt.core.impl.APIMgtAdminServiceImpl;
import org.wso2.carbon.apimgt.core.models.UriTemplate;
import org.wso2.carbon.apimgt.rest.api.core.dto.ResourcesListDTO;
import org.wso2.carbon.apimgt.rest.api.core.utils.SampleTestObjectCreator;
import org.wso2.msf4j.Request;
import org.wso2.transport.http.netty.message.HTTPCarbonMessage;

import javax.ws.rs.core.Response;
import java.util.ArrayList;
import java.util.List;

@RunWith(PowerMockRunner.class)
@PrepareForTest(APIManagerFactory.class)
public class ResourcesApiServiceImplTestCase {

    private static final String API_CONTEXT = "/api";
    private static final String API_VERSION = "1.0.0";

    @Test
    public void resourcesGetTest() throws Exception {
        APIMgtAdminServiceImpl apiMgtAdminService = Mockito.mock(APIMgtAdminServiceImpl.class);
        APIManagerFactory instance = Mockito.mock(APIManagerFactory.class);
        PowerMockito.mockStatic(APIManagerFactory.class);
        PowerMockito.when(APIManagerFactory.getInstance()).thenReturn(instance);
        Mockito.when(instance.getAPIMgtAdminService()).thenReturn(apiMgtAdminService);

        ResourcesApiServiceImpl resourcesApiService = new ResourcesApiServiceImpl();

        UriTemplate uriTemplateOne = SampleTestObjectCreator.createUniqueUriTemplate();
        UriTemplate uriTemplateTwo = SampleTestObjectCreator.createUniqueUriTemplate();
        UriTemplate uriTemplateThree = SampleTestObjectCreator.createUniqueUriTemplate();

        List<UriTemplate> uriTemplateList = new ArrayList<>();
        uriTemplateList.add(uriTemplateOne);
        uriTemplateList.add(uriTemplateTwo);
        uriTemplateList.add(uriTemplateThree);

        Mockito.when(apiMgtAdminService.getAllResourcesForApi(API_CONTEXT, API_VERSION)).thenReturn(uriTemplateList);

        Response response = resourcesApiService.resourcesGet(API_CONTEXT, API_VERSION, null, getRequest());

        Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
        Assert.assertEquals(((ResourcesListDTO) response.getEntity()).getList().size(), 3);

    }

    @Test
    public void resourcesGetApiContextEmptyTest() throws Exception {
        Response response = getResponse(null, API_VERSION);
        Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
        Assert.assertEquals(((ResourcesListDTO) response.getEntity()).getList().size(), 0);

    }

    @Test
    public void resourcesGetApiVersionEmptyTest() throws Exception {
        Response response = getResponse(API_CONTEXT, null);
        Assert.assertEquals(response.getStatus(), Response.Status.OK.getStatusCode());
        Assert.assertEquals(((ResourcesListDTO) response.getEntity()).getList().size(), 0);
    }

    @Test
    public void policiesGetExceptionTest() throws Exception {
        ResourcesApiServiceImpl resourcesApiService = new ResourcesApiServiceImpl();
        Response response = resourcesApiService.resourcesGet(API_CONTEXT, API_VERSION, null, getRequest());
        Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }

    @Test
    public void policiesGetApiContextEmptyExceptionTest() throws Exception {
        ResourcesApiServiceImpl resourcesApiService = new ResourcesApiServiceImpl();
        Response response = resourcesApiService.resourcesGet(null, API_VERSION, null, getRequest());
        Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }

    @Test
    public void policiesGetApiVersionEmptyExceptionTest() throws Exception {
        ResourcesApiServiceImpl resourcesApiService = new ResourcesApiServiceImpl();
        Response response = resourcesApiService.resourcesGet(API_CONTEXT, null, null, getRequest());
        Assert.assertEquals(response.getStatus(), Response.Status.INTERNAL_SERVER_ERROR.getStatusCode());
    }

    private Response getResponse(String apiContext, String apiVersion) throws Exception {
        APIMgtAdminServiceImpl apiMgtAdminService = Mockito.mock(APIMgtAdminServiceImpl.class);
        APIManagerFactory instance = Mockito.mock(APIManagerFactory.class);
        PowerMockito.mockStatic(APIManagerFactory.class);
        PowerMockito.when(APIManagerFactory.getInstance()).thenReturn(instance);
        Mockito.when(instance.getAPIMgtAdminService()).thenReturn(apiMgtAdminService);

        ResourcesApiServiceImpl resourcesApiService = new ResourcesApiServiceImpl();
        return resourcesApiService.resourcesGet(apiContext, apiVersion, null, getRequest());
    }

    private Request getRequest() throws Exception {
        HTTPCarbonMessage carbonMessage = Mockito.mock(HTTPCarbonMessage.class);
        Request request = new Request(carbonMessage);
        PowerMockito.whenNew(Request.class).withArguments(carbonMessage).thenReturn(request);
        return request;
    }

}


text:
using Skybrud.Social.Json;

namespace Skybrud.Social.BitBucket.Objects {

    public class BitBucketAuthor : SocialJsonObject {

        public string Raw { get; private set; }

        public BitBucketAuthorUser User { get; private set; }

        #region Constructors

        private BitBucketAuthor(JsonObject obj) : base(obj) {
            // Hide default constructor
        }

        #endregion

        public static BitBucketAuthor Parse(JsonObject obj) {

            // Check if NULL
            if (obj == null) return null;

            // Initialize the author object
            return new BitBucketAuthor(obj) {
                Raw = obj.GetString("raw"),
                User = obj.GetObject("user", BitBucketAuthorUser.Parse)
            };

        }

    }

}


text:
import collections
import csv
import hashlib
import os

from datetime import datetime

ImportTransaction = collections.namedtuple("ImportTransaction", "date summary amount")

IMPORTS_DIR = "imports"
ARCHIVE_DIR = 'archive'

fields_1 = [
    'status',  # N-New, A-Added, I-Ignored
    'qty',
    'type',
    'transaction_date',
    'posting_date',
    'description',
    'amount'
    ]

#StdImport = collections.namedtuple('StdImport', fields_1)

def hash_row(row):
    h = hashlib.sha1()
    for f in fields_1:
        if f not in ['status', 'qty']:
            h.update(row.get(f, ""))
    return h.hexdigest()

def save_csv(log, additions, field_cfg, date_format):
    """Add any unique entries from new to current"""
    qtys = collections.Counter()
    pool = {}
    log_rows = []
    log_hashes = set()
    for row in csv.DictReader(log):
        log_rows.append(row)
        hash_ = hash_row(row)
        assert hash_ not in log_hashes
        log_hashes.add(hash_)

    dialect = csv.Sniffer().sniff(additions.read(1024))
    additions.seek(0)
    for row in csv.DictReader(additions, dialect=dialect):
        conv_row = {}
        for k, v in row.items():
            if k in field_cfg:
                conv_row[field_cfg[k]] = v.strip()

        conv_row['status'] = 'N'
        date = datetime.strptime(conv_row['transaction_date'], date_format).date()
        conv_row['transaction_date'] = date.strftime('%Y/%m/%d')

        hash_ = hash_row(conv_row)
        if hash_ in log_hashes:
            continue
        pool[hash_] = conv_row
        qtys[hash_] += 1

    for key, val in qtys.items():
        row = pool[key]
        if val > 1:
            row['qty'] = val
        log_rows.append(row)

    log_rows.sort(key=lambda row: (row['transaction_date'], row['description']))

    log.seek(0)
    writer = csv.DictWriter(log, fields_1, lineterminator='\n')
    writer.writeheader()
    for row in log_rows:
        writer.writerow(row)
    log.truncate()

def save(archive_name, input_):
    if not os.path.exists(ARCHIVE_DIR):
        os.mkdir(ARCHIVE_DIR)
    with open(os.path.join(ARCHIVE_DIR, archive_name), 'r+') as archive:
        mapping = {
            'Trans Date': 'transaction_date',
            'Description': 'description',
            'Amount': 'amount'
        }

        save_csv(archive, input_, mapping, '%m/%d/%Y')


text:
/**
 * This class is generated by jOOQ
 */
package com.clevergang.dbtests.repository.impl.jooq.generated.tables.records;

import com.clevergang.dbtests.repository.impl.jooq.generated.tables.Company;

import javax.annotation.Generated;

import org.jooq.Field;
import org.jooq.Record1;
import org.jooq.Record3;
import org.jooq.Row3;
import org.jooq.impl.UpdatableRecordImpl;

/**
 * This class is generated by jOOQ.
 */
@Generated(
    value = {
        "http://www.jooq.org",
        "jOOQ version:3.8.4"
    },
    comments = "This class is generated by jOOQ"
)
@SuppressWarnings({ "all", "unchecked", "rawtypes" })
public class CompanyRecord extends UpdatableRecordImpl<CompanyRecord> implements Record3<Integer, String, String> {

    private static final long serialVersionUID = -1847060208;

    /**
     * Setter for public.company.pid.
     */
    public void setPid(Integer value) {
        set(0, value);
    }

    /**
     * Getter for public.company.pid.
     */
    public Integer getPid() {
        return (Integer) get(0);
    }

    /**
     * Setter for public.company.name.
     */
    public void setName(String value) {
        set(1, value);
    }

    /**
     * Getter for public.company.name.
     */
    public String getName() {
        return (String) get(1);
    }

    /**
     * Setter for public.company.address.
     */
    public void setAddress(String value) {
        set(2, value);
    }

    /**
     * Getter for public.company.address.
     */
    public String getAddress() {
        return (String) get(2);
    }

    // -------------------------------------------------------------------------
    // Primary key information
    // -------------------------------------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public Record1<Integer> key() {
        return (Record1) super.key();
    }

    // -------------------------------------------------------------------------
    // Record3 type implementation
    // -------------------------------------------------------------------------

    /**
     * {@inheritDoc}
     */
    @Override
    public Row3<Integer, String, String> fieldsRow() {
        return (Row3) super.fieldsRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Row3<Integer, String, String> valuesRow() {
        return (Row3) super.valuesRow();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<Integer> field1() {
        return Company.COMPANY.PID;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field2() {
        return Company.COMPANY.NAME;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Field<String> field3() {
        return Company.COMPANY.ADDRESS;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public Integer value1() {
        return getPid();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value2() {
        return getName();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public String value3() {
        return getAddress();
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CompanyRecord value1(Integer value) {
        setPid(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CompanyRecord value2(String value) {
        setName(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CompanyRecord value3(String value) {
        setAddress(value);
        return this;
    }

    /**
     * {@inheritDoc}
     */
    @Override
    public CompanyRecord values(Integer value1, String value2, String value3) {
        value1(value1);
        value2(value2);
        value3(value3);
        return this;
    }

    // -------------------------------------------------------------------------
    // Constructors
    // -------------------------------------------------------------------------

    /**
     * Create a detached CompanyRecord
     */
    public CompanyRecord() {
        super(Company.COMPANY);
    }

    /**
     * Create a detached, initialised CompanyRecord
     */
    public CompanyRecord(Integer pid, String name, String address) {
        super(Company.COMPANY);

        set(0, pid);
        set(1, name);
        set(2, address);
    }
}