text:
local IO = require "kong.tools.io"
local yaml = require "yaml"
local spec_helper = require "spec.spec_helpers"
local config = require "kong.tools.config_loader"

local TEST_CONF_PATH = spec_helper.get_env().conf_file

describe("Configuration validation", function()
  it("should validate the default configuration", function()
    local test_config = yaml.load(IO.read_file(TEST_CONF_PATH))
    local ok, errors = config.validate(test_config)
    assert.True(ok)
    assert.falsy(errors)
  end)
  it("should populate defaults", function()
    local conf = {}
    local ok, errors = config.validate(conf)
    assert.True(ok)
    assert.falsy(errors)

    assert.truthy(conf.custom_plugins)
    assert.truthy(conf.admin_api_listen)
    assert.truthy(conf.proxy_listen)
    assert.truthy(conf.proxy_listen_ssl)
    assert.truthy(conf.cluster_listen)
    assert.truthy(conf.cluster_listen_rpc)
    assert.truthy(conf.database)
    assert.truthy(conf.cassandra)

    local function check_defaults(conf, conf_defaults)
      for k, v in pairs(conf) do
        if conf_defaults[k].type == "table" then
          check_defaults(v, conf_defaults[k].content)
        end
        if conf_defaults[k].default ~= nil then
          assert.equal(conf_defaults[k].default, v)
        end
      end
    end

    check_defaults(conf, require("kong.tools.config_defaults"))
  end)
  it("should populate the plugins property", function()
    local config = config.load(TEST_CONF_PATH)
    assert.truthy(config)
    assert.equal(0, #config.custom_plugins)
    assert.truthy(#config.plugins > 0)
  end)
  it("should validate various types", function()
    local ok, errors = config.validate({
      proxy_listen = 123,
      database = 777,
      cassandra = {
        contact_points = "127.0.0.1",
        ssl = {
          enabled = "false"
        }
      }
    })
    assert.False(ok)
    assert.truthy(errors)
    assert.equal("must be a string", errors.proxy_listen)
    assert.equal("must be a string", errors.database[1])
    assert.equal("must be one of: 'cassandra'", errors.database[2])
    assert.equal("must be a array", errors["cassandra.contact_points"])
    assert.equal("must be a boolean", errors["cassandra.ssl.enabled"])
    assert.falsy(errors.ssl_cert_path)
    assert.falsy(errors.ssl_key_path)
  end)
  it("should check for minimum allowed value if is a number", function()
    local ok, errors = config.validate({memory_cache_size = 16})
    assert.False(ok)
    assert.equal("must be greater than 32", errors.memory_cache_size)
  end)
  it("should check that the value is contained in `enum`", function()
    local ok, errors = config.validate({
      cassandra = {
        replication_strategy = "foo"
      }
    })
    assert.False(ok)
    assert.equal("must be one of: 'SimpleStrategy, NetworkTopologyStrategy'", errors["cassandra.replication_strategy"])
  end)
  it("should validate the selected database property", function()
    local ok, errors = config.validate({database = "foo"})
    assert.False(ok)
    assert.equal("must be one of: 'cassandra'", errors.database)
  end)
  it("should validate the selected dns_resolver property", function()
    local ok, errors = config.validate({dns_resolver = "foo"})
    assert.False(ok)
    assert.equal("must be one of: 'server, dnsmasq'", errors.dns_resolver)
  end)
  it("should validate the host:port listen addresses", function()
    -- Missing port
    local ok, errors = config.validate({proxy_listen = "foo"})
    assert.False(ok)
    assert.equal("foo is not a valid \"host:port\" value", errors.proxy_listen)

    -- Port invalid
    ok, errors = config.validate({proxy_listen = "foo:asd"})
    assert.False(ok)
    assert.equal("foo:asd is not a valid \"host:port\" value", errors.proxy_listen)

    -- Port too large
    ok, errors = config.validate({proxy_listen = "foo:8000000"})
    assert.False(ok)
    assert.equal("foo:8000000 is not a valid \"host:port\" value", errors.proxy_listen)

    -- Only port
    ok, errors = config.validate({proxy_listen = "1231"})
    assert.False(ok)
    assert.equal("1231 is not a valid \"host:port\" value", errors.proxy_listen)

    -- Only semicolon and port
    ok, errors = config.validate({proxy_listen = ":1231"})
    assert.False(ok)
    assert.equal(":1231 is not a valid \"host:port\" value", errors.proxy_listen)

    -- Valid with hostname
    ok, errors = config.validate({proxy_listen = "hello:1231"})
    assert.True(ok)
    assert.falsy(errors)

    -- Valid with IP
    ok, errors = config.validate({proxy_listen = "1.1.1.1:1231"})
    assert.True(ok)
    assert.falsy(errors)
  end)
  it("should validate the ip:port listen addresses", function()
    -- Hostname instead of IP
    local ok, errors = config.validate({cluster_listen = "hello.com:1231"})
    assert.False(ok)
    assert.equal("hello.com:1231 is not a valid \"ip:port\" value", errors.cluster_listen)

    -- Invalid IP
    ok, errors = config.validate({cluster_listen = "777.1.1.1:1231"})
    assert.False(ok)
    assert.equal("777.1.1.1:1231 is not a valid \"ip:port\" value", errors.cluster_listen)

    -- Valid
    ok, errors = config.validate({cluster_listen = "1.1.1.1:1231"})
    assert.True(ok)
    assert.falsy(errors)

    -- Invalid cluster.advertise
    ok, errors = config.validate({cluster={advertise = "1"}})
    assert.False(ok)
    assert.equal("1 is not a valid \"ip:port\" value", errors["cluster.advertise"])

    -- Valid cluster.advertise
    ok, errors = config.validate({cluster={advertise = "1.1.1.1:1231"}})
    assert.True(ok)
    assert.falsy(errors)
  end)
end)


text:
void setLed(uint8_t value);
void setDigit1Segments(uint8_t value);
void setDigit2Segments(uint8_t value);
void setDigit3Segments(uint8_t value);

void displaySplash(void);
void displayDecimalNumber(uint8_t value);
void displayMilivolts(uint16_t value);
void displayHexadecimalNumber(uint8_t value);
void displayOff(void);
void displayBat(void);
void displayDot(void);
void displayNothing(void);

#endif

redpajama_set_name: RedPajamaGithub


text:
layout: default
---
{% include breadcrumbs.html parent="Organizations" %}
{% assign datasets = site.datasets | where:"organization", page.title %}
{% assign datasets_count = datasets | size %}

        {{ page.title }}
        Edit

{{ page.description }}

{{ datasets_count }}
            {% if datasets_count == 1 %}dataset{% else %}datasets{% endif %}

        <input type="text" data-hook="search-query" placeholder="Search..." class="form-control">

         {% for dataset in datasets %}
          <dataset>

{{ dataset.title }}

            {{ dataset.notes }}
          </dataset>
         {% endfor %}

      {% include organization-form.html organization=page %}

      Cancel


text:
import humanApi from 'services/api/human';
import productsApi from 'services/api/products';

import types from './types';

export default {
	giveHumanSomeCash: () => async (dispatch) => {
		dispatch({
			type: types.GIVE_HUMAN_SOME_CASH
		});

		try {
			const cash = await humanApi.getSomeCash();
			dispatch(giveHumanSomeCashOk(cash));
		} catch (exc) {
			dispatch(giveHumanSomeCashFail());
		}
	},

	purchaseProducts: allProducts => (dispatch, getState) => {
		const { cash, purchasedProducts } = getState().human;
		const productsForSale = productsApi.getForSale(allProducts);
		const products = productsApi.merge(purchasedProducts, productsForSale);
		dispatch({
			type: types.PURCHASE_PRODUCTS,
			products,
			cash: +(cash - productsApi.calcSumm(productsForSale)).toFixed(2)
		});
	}
};

const giveHumanSomeCashOk = cash => ({
	type: types.GIVE_HUMAN_SOME_CASH_OK,
	cash
});

const giveHumanSomeCashFail = () => ({
	type: types.GIVE_HUMAN_SOME_CASH_FAIL
});


text:
<?php

/**
 * Convert adapter interface
 *
 * @category   Mage
 * @package    Mage_Dataflow
 * @author      Magento Core Team <core@magentocommerce.com>
 */
interface Mage_Dataflow_Model_Convert_Adapter_Interface
{

    public function load();

    public function save();

}


text:
var contactExport = {};

contactExport.openPhone = function(phoneNumber, successCallback, errorCallback) {
    if (typeof phoneNumber !== 'string' || !(phoneNumber)) {
        if (errorCallback) {
            errorCallback({
                code: "INVALID_INPUT",
                message: "Invalid Input"
            });
        }
        return;
    }

    cordova.exec(successCallback, errorCallback, "ExternalLinks", "openPhone", [phoneNumber.replace(/[^0-9]/gi, '')]);
};

contactExport.openMap = function(param, successCallback, errorCallback) {
    if (typeof param !== 'object') {
        if (errorCallback) {
            errorCallback({
                code: "INVALID_INPUT",
                message: "Invalid Input"
            });
        }
        return;
    }

    cordova.exec(successCallback, errorCallback, "ExternalLinks", "openMap", [param]);
};

module.exports = contactExport;


text:
<?php

/**
 * Inverted Hammer
 *
 * @phpstub
 *
 * @param array $open
 * @param array $high
 * @param array $low
 * @param array $close
 *
 * @return array Returns an array with calculated data or false on failure.
 */
function trader_cdlinvertedhammer($open, $high, $low, $close)
{
}


text:
constexpr unsigned long long powers[] = {
	1ULL,
	10ULL,
	100ULL,
	1000ULL,
	10000ULL,
	100000ULL,
	1000000ULL,
	10000000ULL,
	100000000ULL,
	1000000000ULL,
	10000000000ULL,
	100000000000ULL,
	1000000000000ULL,
	10000000000000ULL,
	100000000000000ULL,
	1000000000000000ULL,
	10000000000000000ULL,
	100000000000000000ULL,
	1000000000000000000ULL,
	10000000000000000000ULL
	};

template <typename Duration, unsigned width>
constexpr bool check_precision()
{
	using HMS = std::chrono::hh_mm_ss<Duration>;
	using CT  = std::common_type_t<typename Duration::rep, std::chrono::seconds::rep>;
	using Pre = std::chrono::duration<CT, std::ratio<1, powers[width]>>;
	return std::is_same_v<typename HMS::precision, Pre>;
}

int main(int, char**)
{
	using microfortnights = std::chrono::duration<int, std::ratio<756, 625>>;

	static_assert( check_precision<std::chrono::hours,                               0>(), "");
	static_assert( check_precision<std::chrono::minutes,                             0>(), "");
	static_assert( check_precision<std::chrono::seconds,                             0>(), "");
	static_assert( check_precision<std::chrono::milliseconds,                        3>(), "");
	static_assert( check_precision<std::chrono::microseconds,                        6>(), "");
	static_assert( check_precision<std::chrono::nanoseconds,                         9>(), "");
	static_assert( check_precision<std::chrono::duration<int, std::ratio<  1,   2>>, 1>(), "");
	static_assert( check_precision<std::chrono::duration<int, std::ratio<  1,   3>>, 6>(), "");
	static_assert( check_precision<std::chrono::duration<int, std::ratio<  1,   4>>, 2>(), "");
	static_assert( check_precision<std::chrono::duration<int, std::ratio<  1,   5>>, 1>(), "");
	static_assert( check_precision<std::chrono::duration<int, std::ratio<  1,   6>>, 6>(), "");
	static_assert( check_precision<std::chrono::duration<int, std::ratio<  1,   7>>, 6>(), "");
	static_assert( check_precision<std::chrono::duration<int, std::ratio<  1,   8>>, 3>(), "");
	static_assert( check_precision<std::chrono::duration<int, std::ratio<  1,   9>>, 6>(), "");
	static_assert( check_precision<std::chrono::duration<int, std::ratio<  1,  10>>, 1>(), "");
	static_assert( check_precision<microfortnights,                                  4>(), "");

	return 0;
}


text:
package io.undertow.predicate;

import io.undertow.server.HttpServerExchange;

/**
 * @author Stuart Douglas
 */
public class TruePredicate implements Predicate {

    public static final TruePredicate INSTANCE = new TruePredicate();

    public static TruePredicate instance() {
        return INSTANCE;
    }

    @Override
    public boolean resolve(final HttpServerExchange value) {
        return true;
    }
}


text:
<?php
include_once 'functions.php';
include_once 'follow.php';

sec_session_start();

$me = $_SESSION['username'];
$theirid = $_GET['id'];
$myid = $_SESSION['user_id'];
$them = $_GET['name'];
$do = $_GET['do'];

switch ($do){

	case "unfollow":
		unfollow_user($theirid, $me, $them, $mysqli);
		$msg = "You have unfollowed " . $them;
	break;

	case "follow":
		follow_user($theirid, $myid, $me, $them, $mysqli);
		$msg = "You have followed " . $them;
	break;

	default:
		$msg = "";

}

$_SESSION['message'] = $msg;

$backURL = empty($_SESSION['backURL']) ? '/' : $_SESSION['backURL'];
unset($_SESSION['backURL']);
header('Location: ' . $backURL);

?>


text:
package com.hirain.websocket.socket;

import java.util.Map;

import javax.servlet.http.HttpSession;

import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.http.server.ServletServerHttpRequest;
import org.springframework.web.socket.WebSocketHandler;
import org.springframework.web.socket.server.HandshakeInterceptor;

public class WebSocketInterceptor implements HandshakeInterceptor {

	@Override
	public void afterHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1,
			WebSocketHandler arg2, Exception arg3) {

	}

	@Override
	public boolean beforeHandshake(ServerHttpRequest arg0, ServerHttpResponse arg1,
			WebSocketHandler arg2, Map<String, Object> arg3) throws Exception {
		if (arg0 instanceof ServerHttpRequest) {
			final ServletServerHttpRequest servletRequest = (ServletServerHttpRequest) arg0;
			final HttpSession session = servletRequest.getServletRequest().getSession();
			if (session != null) {
				arg3.put("user", session.getAttribute("user"));
			}
		}
		return true;
	}

}


text:
#include "DS_Array.h"
#include "DS_Config.h"
#include "DS_Events.h"
#include "DS_Joysticks.h"

#include <stdio.h>

/**
 * Represents a joystick and its information
 */
typedef struct _joystick
{
   int *hats; /**< An array with the hat angles */
   float *axes; /**< An array with the axis values */
   int *buttons; /**< An array with the button states */
   int num_axes; /**< The number of axes of the joystick */
   int num_hats; /**< The number of hats of the joystick */
   int num_buttons; /**< The number of buttons of the joystick */
} DS_Joystick;

/**
 * Holds all the joysticks
 */
static DS_Array array;

/**
 * Registers a joystick event to the LibDS event system
 */
static void register_event()
{
   DS_Event event;
   event.joystick.count = DS_GetJoystickCount();
   event.joystick.type = DS_JOYSTICK_COUNT_CHANGED;
   DS_AddEvent(&event);
}

/**
 * Returns the joystick structure at the given index
 * If the joystick does not exist, this function shall return \c NULL
 */
static DS_Joystick *get_joystick(int joystick)
{
   if ((int)array.used > joystick)
      return (DS_Joystick *)array.data[joystick];

   return NULL;
}

/**
 * Returns \c true if the given \a joystick exists and is valid
 */
static int joystick_exists(int joystick)
{
   if (DS_GetJoystickCount() > joystick)
      return get_joystick(joystick) != NULL;

   return 0;
}

/**
 * Initializes the joystick array, with an initial support for 6 joysticks
 */
void Joysticks_Init(void)
{
   DS_ArrayInit(&array, 6);
}

/**
 * De-allocates the joystick array data
 */
void Joysticks_Close(void)
{
   DS_ArrayFree(&array);
   register_event();
}

/**
 * Returns the number of joysticks registered with the LibDS
 */
int DS_GetJoystickCount(void)
{
   return (int)array.used;
}

/**
 * Returns the number of hats that the given \a joystick has.
 * If the joystick does not exist, this function will return \c 0
 */
int DS_GetJoystickNumHats(int joystick)
{
   if (joystick_exists(joystick))
      return get_joystick(joystick)->num_hats;

   return 0;
}

/**
 * Returns the number of axes that the given \a joystick has.
 * If the joystick does not exist, this function will return \c 0
 */
int DS_GetJoystickNumAxes(int joystick)
{
   if (joystick_exists(joystick))
      return get_joystick(joystick)->num_axes;

   return 0;
}

/**
 * Returns the number of buttons that the given \a joystick has.
 * If the joystick does not exist, this function will return \c 0
 */
int DS_GetJoystickNumButtons(int joystick)
{
   if (joystick_exists(joystick))
      return get_joystick(joystick)->num_buttons;

   return 0;
}

/**
 * Returns the value that the given \a hat in the given \a joystick has.
 * If the joystick or hat do not exist, this function will return \c 0
 *
 * \note Regardless of protocol implementation, this function will return
 *       a neutral value if the robot is disabled. This is for additional
 *       safety!
 */
int DS_GetJoystickHat(int joystick, int hat)
{
   if (CFG_GetRobotEnabled() && joystick_exists(joystick))
   {
      DS_Joystick *stick = get_joystick(joystick);

      if (stick->num_hats > hat)
         return stick->hats[hat];
   }

   return 0;
}

/**
 * Returns the value that the given \a axis in the given \a joystick has.
 * If the joystick or axis do not exist, this function will return \c 0
 *
 * \note Regardless of protocol implementation, this function will return
 *       a neutral value if the robot is disabled. This is for additional
 *       safety!
 */
float DS_GetJoystickAxis(int joystick, int axis)
{
   if (CFG_GetRobotEnabled() && joystick_exists(joystick))
   {
      DS_Joystick *stick = get_joystick(joystick);

      if (stick->num_axes > axis)
         return stick->axes[axis];
   }

   return 0;
}

/**
 * Returns the value that the given \a button in the given \a joystick has.
 * If the joystick or button do not exist, this function will return \c 0
 *
 * \note Regardless of protocol implementation, this function will return
 *       a neutral value if the robot is disabled. This is for additional
 *       safety!
 */
int DS_GetJoystickButton(int joystick, int button)
{
   if (CFG_GetRobotEnabled() && joystick_exists(joystick))
   {
      DS_Joystick *stick = get_joystick(joystick);

      if (stick->num_buttons > button)
         return stick->buttons[button];
   }

   return 0;
}

/**
 * Removes all the registered joysticks from the LibDS
 */
void DS_JoysticksReset(void)
{
   DS_ArrayFree(&array);
   DS_ArrayInit(&array, 6);

   register_event();
}

/**
 * Registers a new joystick with the given number of \a axes, \a hats and
 * \a buttons. All joystick values are set to a neutral state to ensure
 * safe operation of the robot.
 */
void DS_JoysticksAdd(const int axes, const int hats, const int buttons)
{
   /* Joystick is empty */
   if (axes <= 0 && hats <= 0 && buttons <= 0)
   {
      fprintf(stderr, "DS_JoystickAdd: Cannot register empty joystick!\n");
      return;
   }

   /* Allocate memory for a new joystick */
   DS_Joystick *joystick = (DS_Joystick *)calloc(1, sizeof(DS_Joystick));

   /* Set joystick properties */
   joystick->num_axes = axes;
   joystick->num_hats = hats;
   joystick->num_buttons = buttons;

   /* Set joystick value arrays */
   joystick->hats = calloc(hats, sizeof(int));
   joystick->axes = calloc(axes, sizeof(float));
   joystick->buttons = calloc(buttons, sizeof(int));

   /* Register the new joystick in the joystick list */
   DS_ArrayInsert(&array, (void *)joystick);

   /* Emit the joystick count changed event */
   register_event();
}

/**
 * Updates the \a angle of the given \a hat in the given \a joystick
 */
void DS_SetJoystickHat(int joystick, int hat, int angle)
{
   if (joystick_exists(joystick))
   {
      DS_Joystick *stick = get_joystick(joystick);

      if (stick->num_hats > hat)
         stick->hats[hat] = angle;
   }
}

/**
 * Updates the \a value of the given \a axis in the given \a joystick
 */
void DS_SetJoystickAxis(int joystick, int axis, float value)
{
   if (joystick_exists(joystick))
   {
      DS_Joystick *stick = get_joystick(joystick);

      if (stick->num_axes > axis)
         stick->axes[axis] = value;
   }
}

/**
 * Updates the \a pressed state of the given \a button in the given \a joystick
 */
void DS_SetJoystickButton(int joystick, int button, int pressed)
{
   if (joystick_exists(joystick))
   {
      DS_Joystick *stick = get_joystick(joystick);

      if (stick->num_buttons > button)
         stick->buttons[button] = (pressed > 0) ? 1 : 0;
   }
}


text:
<?php

use yii\helpers\Html;
use yii\widgets\ActiveForm;
use yii\helpers\Url;
/* @var $this yii\web\View */
/* @var $model app\models\Special */
/* @var $form yii\widgets\ActiveForm */
?>

    <?php $form = ActiveForm::begin([
    'options' => ['enctype' => 'multipart/form-data', 'class' => ""]
    ]); ?>

  <?= $form->field($model, 'name')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'old_price')->textInput() ?>

    <?= $form->field($model, 'new_price')->textInput() ?>

    <?= $form->field($model, 'seats')->textInput(['maxlength' => true]) ?>

    <?= $form->field($model, 'description')->textarea(['rows' => 6]) ?>
<?php if(isset($model->photo_url)):?>

          <img class="img-responsive" src="<?=Url::to('@web/src/special/') . $model->photo_url?>">

  <?php endif; ?>
  <input type="file" name="file">

        <?= Html::submitButton($model->isNewRecord ? 'Create' : 'Update', ['class' => $model->isNewRecord ? 'btn btn-success' : 'btn btn-primary']) ?>

    <?php ActiveForm::end(); ?>


text:
require 'spec_helper'

describe Function::Numeric::Multiplication, '.call' do
  subject { object.call(left, right) }

  let(:object) { described_class }
  let(:left)   { 2               }
  let(:right)  { 2               }

  it { should eql(4) }
end


text:
module BootstrapModalHelper
  module Rails
    VERSION = "0.1.0"
  end
end


text:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">

    <item  android:id="@+id/edit"
        android:title="Edit"/>

    <item  android:id="@+id/delete"
        android:title="Delete"/>

    <item  android:id="@+id/map"
        android:title="Map"/>

</menu>


text:
import { moduleForModel, test } from 'ember-qunit';

moduleForModel('capability-statement-supported-message', 'Unit | Model | CapabilityStatement_SupportedMessage', {
  needs: [
    'model:meta',
    'model:narrative',
    'model:resource',
    'model:extension',
    'model:reference'
  ]
});

test('it exists', function(assert) {
  const model = this.subject();
  assert.ok(!!model);
});


text:
package se.liquidbytes.jel.system.adapter;

import com.cyngn.vertx.async.Latch;
import com.cyngn.vertx.async.promise.Promise;
import com.fasterxml.jackson.databind.ObjectMapper;
import io.vertx.core.DeploymentOptions;
import io.vertx.core.Future;
import io.vertx.core.eventbus.DeliveryOptions;
import io.vertx.core.json.JsonObject;
import java.io.File;
import java.io.IOException;
import java.lang.invoke.MethodHandles;
import java.nio.file.Files;
import java.nio.file.LinkOption;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;
import java.util.Optional;
import java.util.concurrent.CopyOnWriteArrayList;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import se.liquidbytes.jel.JelException;
import se.liquidbytes.jel.Settings;
import se.liquidbytes.jel.system.InternalEvents;
import se.liquidbytes.jel.system.JelService;
import se.liquidbytes.jel.system.plugin.PluginDesc;

/**
 * Class that loads and keeps track of all adapterDescriptions.
 *
 * @author Henrik Östman
 */
public final class AdapterManager {

  /**
   * File of all adapterDescriptions. Loaded at applicationstart, and updated every time we add a new AdapterConfiguration.
   */
  private final static String ADAPTERS_FILE = "adapters.json";

  /**
   * Logghandler instance
   */
  private final static Logger logger = LoggerFactory.getLogger(MethodHandles.lookup().lookupClass());

  /**
   * Collection of all adapters.
   */
  private final Map<String, List<DeployedAdapter>> adapters;  // Adaptertype name as key.

  /**
   * Collection of all plugins of adapter-type.
   */
  private final Map<String, PluginDesc> adapterTypes; // Adaptertype name as key.

  /**
   * ObjectMapper instance for loading and storing settings-files.
   */
  private final ObjectMapper objectMapper;

  /**
   * Collection of settings for adapters.
   */
  private AdapterSettingsList adaptersSettings;

  /**
   * Path to file containing configuration about all adapters that should be loaded (adapters.json).
   */
  private Path adapterFilePath;

  /**
   * Default constructor.
   */
  public AdapterManager() {
    adapters = new LinkedHashMap<>();
    adapterTypes = new LinkedHashMap<>();
    adaptersSettings = new AdapterSettingsList();
    objectMapper = new ObjectMapper();
  }

  /**
   * Method for starting adapter manager, should be called upon application startup.
   */
  public void start() {

    adapterFilePath = Paths.get(Settings.getStoragePath().toString(), File.separator, ADAPTERS_FILE);

    if (Files.exists(adapterFilePath, LinkOption.NOFOLLOW_LINKS)) {
      logger.info("Loading adapters settings from '{}'", adapterFilePath);

      try {
        byte[] fileContent = Files.readAllBytes(adapterFilePath);
        adaptersSettings = objectMapper.readValue(fileContent, AdapterSettingsList.class);
      } catch (IOException ex) {
        throw new JelException(String.format("Failed to load adapters settings from '%s'", adapterFilePath), ex);
      }

      // Clean list from invalid entries.
      List<AdapterConfiguration> cleanConfig = new CopyOnWriteArrayList<>();
      for (AdapterConfiguration config : adaptersSettings.getAdapters()) {
        if (!cleanConfig.contains(config)
            && config.getType() != null && !config.getType().isEmpty()
            && config.getAddress() != null && !config.getAddress().isEmpty()) {
          cleanConfig.add(config);
        }
      }
      // If lists missmatch in size, then update our config-list and update config-file so that we maybe get a correct one next time.
      if (adaptersSettings.getAdapters().size() != cleanConfig.size()) {
        adaptersSettings.setAdapters(cleanConfig);
        try {
          objectMapper.writer().withDefaultPrettyPrinter().writeValue(adapterFilePath.toFile(), adaptersSettings);
        } catch (IOException ex) {
          throw new JelException(String.format("Failed to save cleaned file '%s'.", ADAPTERS_FILE), ex);
        }
      }
    } else {
      try {
        // "adapters.json"-file does not exist, so we create it.
        objectMapper.writeValue(adapterFilePath.toFile(), adaptersSettings);
      } catch (IOException ex) {
        throw new JelException(String.format("Failed to create file '%s'.", ADAPTERS_FILE), ex);
      }
    }
  }

  /**
   * Method for stopping adapter manager, should be called upon application shutdown.
   *
   * @param stopFuture Optional future that will be called when shutdown has succeeded or failed. Set to null if not needed.
   */
  public void stop(Future<Void> stopFuture) {

    logger.info("Shutting down adapters and adaptermanager...");

    Latch latch = new Latch(adapters.values().size(), () -> {
      logger.debug("All adapters stopped.");
      if (stopFuture != null) {
        stopFuture.complete();
      }
    });

    for (List<DeployedAdapter> adapterType : adapters.values()) {
      for (DeployedAdapter adapter : adapterType) {
        JelService.vertx().undeploy(adapter.deploymentId(), res -> {
          if (res.succeeded()) {
            logger.info("Stopped verticle for adapter '{}' using addess '{}' and port '{}'.", adapter.config().getType(), adapter.config().getAddress(), adapter.config().getPort());
          } else {
            logger.warn("Failed to stop verticle for adapter '{}' using addess '{}' and port '{}'.", adapter.config().getType(), adapter.config().getAddress(), adapter.config().getPort(), res.cause());
          }

          latch.complete();
        });
      }
    }
  }

  /**
   * Get available adaptertypes.
   *
   * @return collection of adaptertypes.
   */
  public List<PluginDesc> getAvailableAdapterTypes() {
    synchronized (adapterTypes) {
      return new CopyOnWriteArrayList(adapterTypes.values());
    }
  }

  /**
   * Register a plugin of type adapter. This should only be used by the plugin manager.
   *
   * @param adapterType adapter-plugin.
   */
  public void registerAdapterTypePlugin(PluginDesc adapterType) {
    synchronized (adapterTypes) {
      if (adapterTypes.get(adapterType.getName()) == null) {

        logger.info("Adding new adaptertype '{}'.", adapterType.getName());
        adapterTypes.put(adapterType.getName(), adapterType);

        JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, adapterType.toApi(), new DeliveryOptions().addHeader("action", InternalEvents.EVENT_ADAPTERTYPE_ADDED));

        startAdapters(adapterType);
      }
    }
  }

  /**
   * Unregister a plugin of type adapter. This should only be used by the plugin manager.
   *
   * @param adapterType adapter-plugin.
   */
  public void unregisterAdapterTypePlugin(PluginDesc adapterType) {
    synchronized (adapterTypes) {
      PluginDesc type = adapterTypes.get(adapterType.getName());

      if (type != null) {

        logger.info("Removing existing adaptertype '{}'.", type.getName());
        adapterTypes.remove(type.getName());

        JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, adapterType.toApi(), new DeliveryOptions().addHeader("action", InternalEvents.EVENT_ADAPTERTYPE_REMOVED));

        stopAdapters(adapterType);
      }
    }
  }

  /**
   * Returns the list with information of all adapters.
   *
   * @return All adapters
   */
  public synchronized List<DeployedAdapter> getAdapters() {
    List<DeployedAdapter> deployedAdapters = new ArrayList<>();

    Iterator<List<DeployedAdapter>> it = adapters.values().iterator();
    while (it.hasNext()) {
      deployedAdapters.addAll(it.next());
    }

    return deployedAdapters;
  }

  /**
   * Returns adapter with specified id.
   *
   * @param id id for requested adapter.
   * @return Adapter having specified id, or null if none found.
   */
  public synchronized DeployedAdapter getAdapter(String id) {
    DeployedAdapter foundAdapter = null;

    Iterator<List<DeployedAdapter>> adapterTypeFamily = adapters.values().iterator();
    while (adapterTypeFamily.hasNext() && foundAdapter == null) {
      Iterator<DeployedAdapter> deployedAdapters = adapterTypeFamily.next().iterator();
      while (deployedAdapters.hasNext() && foundAdapter == null) {
        foundAdapter = deployedAdapters.next();
        if (!foundAdapter.Id().equals(id)) {
          foundAdapter = null;
        }
      }
    }

    return foundAdapter;
  }

  /**
   * Add config for and start a new adapter
   *
   * @param config config for adapter to start
   * @throws JelException if failed to add adapter.
   */
  public void addAdapter(AdapterConfiguration config) {
    if (config == null) {
      throw new JelException("No initialized config provided.");
    }
    if (config.getType() == null || config.getType().isEmpty()) {
      throw new JelException("No adaptertype provided.");
    }
    if (config.getAddress() == null || config.getAddress().isEmpty()) {
      throw new JelException("No adapteraddress provided.");
    }

    List<AdapterConfiguration> existingAdapters = adaptersSettings.getAdapters();

    if (!existingAdapters.contains(config)) {
      existingAdapters.add(config);

      adaptersSettings.setAdapters(existingAdapters);

      try {
        objectMapper.writer().withDefaultPrettyPrinter().writeValue(adapterFilePath.toFile(), adaptersSettings);
        startAdapter(config);

        JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, config.toApi(), new DeliveryOptions().addHeader("action", InternalEvents.EVENT_ADAPTER_ADDED));
      } catch (IOException ex) {
        existingAdapters.remove(config);
        throw new JelException(String.format("Failed to add adapterconfiguration to %s.", adapterFilePath), ex);
      }
    }
  }

  /**
   * Remove config for and stop a existing adapter.
   *
   * @param id id of existing adapter.
   * @throws JelException if failed to remove adapter.
   */
  public void removeAdapter(String id) {
    if (id == null || id.isEmpty()) {
      throw new JelException("No id for adapter provided.");
    }

    DeployedAdapter deployedAdapter = this.getAdapter(id);

    if (deployedAdapter != null) {
      List<AdapterConfiguration> existingAdapters = adaptersSettings.getAdapters();
      AdapterConfiguration config = deployedAdapter.config();
      existingAdapters.remove(config);

      adaptersSettings.setAdapters(existingAdapters);

      try {
        objectMapper.writer().withDefaultPrettyPrinter().writeValue(adapterFilePath.toFile(), adaptersSettings);
        stopAdapter(config);

        JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, config.toApi(), new DeliveryOptions().addHeader("action", InternalEvents.EVENT_ADAPTER_REMOVED));
      } catch (IOException ex) {
        existingAdapters.add(config);
        throw new JelException(String.format("Failed to removed adapterconfiguration from %s.", adapterFilePath), ex);
      }
    }
  }

  /**
   * Stops verticles for adaptertype. We take care of stopping all affected verticles running this/these adapters.
   *
   * @param adapterType if a adaptertype (plugin) has been unregistered, pass its plugin description to this method.
   */
  private void stopAdapters(PluginDesc adapterType) {
    if (adapterType != null) {
      List<DeployedAdapter> adapterList = adapters.get(adapterType.getName());

      if (adapterList != null) {
        for (DeployedAdapter adapter : adapterList) {
          JelService.vertx().undeploy(adapter.deploymentId(), res -> {
            if (res.succeeded()) {
              adapterList.remove(adapter);
              logger.info("Stopped verticle for adapter '{}' using addess '{}' and port '{}'.", adapter.config().getType(), adapter.config().getAddress(), adapter.config().getPort());
              JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, adapter.toApi(), new DeliveryOptions().addHeader("action", InternalEvents.EVENT_ADAPTER_STOPPED));
            } else {
              logger.error("Failed to stop verticle for adapter '{}' using addess '{}' and port '{}'.", adapter.config().getType(), adapter.config().getAddress(), adapter.config().getPort(), res.cause());
            }
          });
        }
      }
    }
  }

  /**
   * Stops verticle for adapter. We take care of stopping the affected verticle running this adapter.
   *
   * @param adapterSettings if a single adapter has been removed then pass its adapterSetting to this method.
   */
  private void stopAdapter(AdapterConfiguration adapterSettings) {
    if (adapterSettings != null) {
      for (List<DeployedAdapter> adapterInstances : adapters.values()) {
        for (DeployedAdapter adapter : adapterInstances) {
          if (adapter.equals(adapterSettings)) {
            JelService.vertx().undeploy(adapter.deploymentId(), res -> {
              if (res.succeeded()) {
                adapterInstances.remove(adapter);
                logger.info("Stopped verticle for adapter '{}' using addess '{}' and port '{}'.", adapter.config().getType(), adapter.config().getAddress(), adapter.config().getPort());
                JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, adapter.toApi(), new DeliveryOptions().addHeader("action", InternalEvents.EVENT_ADAPTER_STOPPED));
              } else {
                logger.error("Failed to stop verticle for adapter '{}' using addess '{}' and port '{}'.", adapter.config().getType(), adapter.config().getAddress(), adapter.config().getPort(), res.cause());
              }
            });
          }
        }
      }
    }
  }

  /**
   * Starts verticles for adaptertypes based upon the available adaptertypes and which adapters that should be running according to the adapters.json-file.
   *
   * @param adapterType if a adaptertype (plugin) has been registered, pass its plugin description to this method.
   */
  private void startAdapters(PluginDesc adapterType) {
    if (adapterType != null && adapterTypes.containsKey(adapterType.getName())) {
      List<AdapterConfiguration> configurations = adaptersSettings.getAdapters();

      if (!adapters.containsKey(adapterType.getName())) {
        adapters.put(adapterType.getName(), new CopyOnWriteArrayList<>());
      }

      List<DeployedAdapter> adapterList = adapters.get(adapterType.getName());

      Promise promise = JelService.promiseFactory().create();

      for (AdapterConfiguration adapterConfig : configurations) {
        // Check that we only try to start adapters in config that are of our requested type.
        if (adapterConfig.getType().equals(adapterType.getName())) {
          promise.then((context, onResult) -> {
            AdapterConfiguration adapterToStart = adapterConfig;

            // Don't try to start the same adapter (same settings) multiple times.
            for (DeployedAdapter adapter : adapterList) {
              if (adapter.equals(adapterConfig)) {
                adapterToStart = null;  // An adapter with these settings are already running, so set this variable to not start.
                break;
              }
            }

            if (adapterToStart != null) {

              try {
                AbstractAdapter adapterInstance = (AbstractAdapter) JelService.pluginManager().getPluginsInstance(adapterType, true);

                JsonObject config = new JsonObject();
                config.put("type", adapterToStart.getType());          // Name of adaptertype.
                config.put("address", adapterToStart.getAddress());    // Address of adapter, could be a network TCP/IP address, but also the type of a physical port e.g. "/dev/ttyS0".
                config.put("port", adapterToStart.getPort());          // Optional port of adapter, most commonly used by networked based adapter.
                AdapterConfiguration deployedConfig = new AdapterConfiguration(config);

                DeployedAdapter adapter = new DeployedAdapter();
                adapter.config(deployedConfig);
                adapter.setPluginDescription(adapterType);

                // Stupid circular dependencies, but now we finally has the adapter id.
                config.put("adapterId", adapter.Id());

                DeploymentOptions deployOptions = new DeploymentOptions();
                deployOptions.setConfig(config);
                deployOptions.setInstances(1);
                deployOptions.setWorker(true);

                JelService.vertx().deployVerticle(adapterInstance, deployOptions, res -> {
                  if (res.succeeded()) {
                    logger.info("Successfully deployed verticle with id: {}, for adapter '{}' using address '{}' and port '{}'.",
                        res.result(), deployedConfig.getType(), deployedConfig.getAddress(), deployedConfig.getPort());

                    adapter.deploymentId(res.result());

                    adapterList.add(adapter);

                    JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, adapter.toApi(), new DeliveryOptions().addHeader("action", InternalEvents.EVENT_ADAPTER_STARTED));
                    onResult.accept(true);
                  } else {
                    logger.error("Failed to deploy verticle for adapter '{}' using address '{}' and port '{}'.",
                        deployedConfig.getType(), deployedConfig.getAddress(), deployedConfig.getPort(), res.cause());
                    // Continue deploying other adapters.
                    onResult.accept(true);
                  }
                });
              } catch (ClassCastException exception) {
                logger.error("Plugin, {}, is said to be a adapter but does not inheritage from AbstractAdapter-class, this must be fixed by plugin developer! Adapter will not be started.", adapterType.getName(), exception);
                // Continue deploying other adapters.
                onResult.accept(true);
              }
            } else {
              // This adapter is already running so continue deploying other adapters.
              onResult.accept(true);
            }
          });
        }
      }
      // Start deploying adapters serially.
      promise.eval();
    }
  }

  /**
   * Starts verticle for adapter based upon which adapters that should be running according to the adapters.json-file.
   *
   * @param adapterConfig configuration of adapter.
   */
  private void startAdapter(AdapterConfiguration adapterConfig) {
    if (adapterConfig != null) {
      Optional<PluginDesc> plugin = JelService.pluginManager().getInstalledPlugins().stream().filter(
          a -> a.getName().equals(adapterConfig.getType())
      ).findFirst();
      if (!plugin.isPresent()) {
        logger.debug("No adaptertype with name '{}' registered yet, skipping this adapter.", adapterConfig.getType());
      } else {
        try {
          AbstractAdapter adapterInstance = (AbstractAdapter) JelService.pluginManager().getPluginsInstance(plugin.get(), true);

          JsonObject config = new JsonObject();
          config.put("type", adapterConfig.getType());          // Name of adaptertype.
          config.put("address", adapterConfig.getAddress());    // Address of adapter, could be a network TCP/IP address, but also the type of a physical port e.g. "/dev/ttyS0".
          config.put("port", adapterConfig.getPort());          // Optional port of adapter, most commonly used by networked based adapter.
          AdapterConfiguration deployedConfig = new AdapterConfiguration(config);

          DeployedAdapter adapter = new DeployedAdapter();
          adapter.config(deployedConfig);
          adapter.setPluginDescription(plugin.get());

          // Stupid circular dependencies, but now we finally has the adapter id.
          config.put("adapterId", adapter.Id());

          DeploymentOptions deployOptions = new DeploymentOptions();
          deployOptions.setConfig(config);
          deployOptions.setInstances(1);
          deployOptions.setWorker(true);

          JelService.vertx().deployVerticle(adapterInstance, deployOptions, res -> {
            if (res.succeeded()) {
              logger.info("Successfully deployed verticle with id: {}, for adapter '{}' using address '{}' and port '{}'.",
                  res.result(), deployedConfig.getType(), deployedConfig.getAddress(), deployedConfig.getPort());

              if (!adapters.containsKey(deployedConfig.getType())) {
                adapters.put(deployedConfig.getType(), new CopyOnWriteArrayList<>());
              }

              List<DeployedAdapter> adapterList = adapters.get(deployedConfig.getType());

              adapter.deploymentId(res.result());

              adapterList.add(adapter);

              JelService.vertx().eventBus().publish(InternalEvents.EVENTBUS_INTERNAL, adapter.toApi(), new DeliveryOptions().addHeader("action", InternalEvents.EVENT_ADAPTER_STARTED));
            } else {
              logger.error("Failed to deploy verticle for adapter '{}' using address '{}' and port '{}'.",
                  deployedConfig.getType(), deployedConfig.getAddress(), deployedConfig.getPort(), res.cause());
            }
          });
        } catch (ClassCastException exception) {
          logger.error("Plugin, {}, is said to be a adapter but does not inheritage from AbstractAdapter-class, this must be fixed by plugin developer! Adapter will not be started.", plugin.get().getName(), exception);
        }
      }
    }
  }
}


text:
local M = { }
local name1 = "directory"
local name2 = "cart"
local TK = require("PackageToolkit")
local FX = require("FunctionalX")
M.case = function(inputs, solution, msg)
  if msg == nil then
    msg = ""
  end
  print(TK.ui.dashed_line(80, '-'))
  print(string.format("test %s.%s()", name1, name2))
  print(msg)
  local result = FX[name1][name2](unpack(inputs))
  print("Result:", unpack(result))
  print("Solution:", unpack(solution))
  assert(TK.test.equal_lists(result, solution))
  print("VERIFIED!")
  return print(TK.ui.dashed_line(80, '-'))
end
return M


text:
package proto_test

import (
	"strings"
	"testing"

	"github.com/insionng/yougam/libraries/golang/protobuf/proto"

	pb "github.com/insionng/yougam/libraries/golang/protobuf/proto/proto3_proto"
	testpb "github.com/insionng/yougam/libraries/golang/protobuf/proto/testdata"
	anypb "github.com/insionng/yougam/libraries/golang/protobuf/ptypes/any"
)

var (
	expandedMarshaler        = proto.TextMarshaler{ExpandAny: true}
	expandedCompactMarshaler = proto.TextMarshaler{Compact: true, ExpandAny: true}
)

// anyEqual reports whether two messages which may be google.protobuf.Any or may
// contain google.protobuf.Any fields are equal. We can't use proto.Equal for
// comparison, because semantically equivalent messages may be marshaled to
// binary in different tag order. Instead, trust that TextMarshaler with
// ExpandAny option works and compare the text marshaling results.
func anyEqual(got, want proto.Message) bool {
	// if messages are proto.Equal, no need to marshal.
	if proto.Equal(got, want) {
		return true
	}
	g := expandedMarshaler.Text(got)
	w := expandedMarshaler.Text(want)
	return g == w
}

type golden struct {
	m    proto.Message
	t, c string
}

var goldenMessages = makeGolden()

func makeGolden() []golden {
	nested := &pb.Nested{Bunny: "Monty"}
	nb, err := proto.Marshal(nested)
	if err != nil {
		panic(err)
	}
	m1 := &pb.Message{
		Name:        "David",
		ResultCount: 47,
		Anything:    &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb},
	}
	m2 := &pb.Message{
		Name:        "David",
		ResultCount: 47,
		Anything:    &anypb.Any{TypeUrl: "http://[::1]/type.googleapis.com/" + proto.MessageName(nested), Value: nb},
	}
	m3 := &pb.Message{
		Name:        "David",
		ResultCount: 47,
		Anything:    &anypb.Any{TypeUrl: `type.googleapis.com/"/` + proto.MessageName(nested), Value: nb},
	}
	m4 := &pb.Message{
		Name:        "David",
		ResultCount: 47,
		Anything:    &anypb.Any{TypeUrl: "type.googleapis.com/a/path/" + proto.MessageName(nested), Value: nb},
	}
	m5 := &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(nested), Value: nb}

	any1 := &testpb.MyMessage{Count: proto.Int32(47), Name: proto.String("David")}
	proto.SetExtension(any1, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("foo")})
	proto.SetExtension(any1, testpb.E_Ext_Text, proto.String("bar"))
	any1b, err := proto.Marshal(any1)
	if err != nil {
		panic(err)
	}
	any2 := &testpb.MyMessage{Count: proto.Int32(42), Bikeshed: testpb.MyMessage_GREEN.Enum(), RepBytes: [][]byte{[]byte("roboto")}}
	proto.SetExtension(any2, testpb.E_Ext_More, &testpb.Ext{Data: proto.String("baz")})
	any2b, err := proto.Marshal(any2)
	if err != nil {
		panic(err)
	}
	m6 := &pb.Message{
		Name:        "David",
		ResultCount: 47,
		Anything:    &anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},
		ManyThings: []*anypb.Any{
			&anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any2), Value: any2b},
			&anypb.Any{TypeUrl: "type.googleapis.com/" + proto.MessageName(any1), Value: any1b},
		},
	}

	const (
		m1Golden = `
name: "David"
result_count: 47
anything: <
  [type.googleapis.com/proto3_proto.Nested]: <
    bunny: "Monty"
  >
>
`
		m2Golden = `
name: "David"
result_count: 47
anything: <
  ["http://[::1]/type.googleapis.com/proto3_proto.Nested"]: <
    bunny: "Monty"
  >
>
`
		m3Golden = `
name: "David"
result_count: 47
anything: <
  ["type.googleapis.com/\"/proto3_proto.Nested"]: <
    bunny: "Monty"
  >
>
`
		m4Golden = `
name: "David"
result_count: 47
anything: <
  [type.googleapis.com/a/path/proto3_proto.Nested]: <
    bunny: "Monty"
  >
>
`
		m5Golden = `
[type.googleapis.com/proto3_proto.Nested]: <
  bunny: "Monty"
>
`
		m6Golden = `
name: "David"
result_count: 47
anything: <
  [type.googleapis.com/testdata.MyMessage]: <
    count: 47
    name: "David"
    [testdata.Ext.more]: <
      data: "foo"
    >
    [testdata.Ext.text]: "bar"
  >
>
many_things: <
  [type.googleapis.com/testdata.MyMessage]: <
    count: 42
    bikeshed: GREEN
    rep_bytes: "roboto"
    [testdata.Ext.more]: <
      data: "baz"
    >
  >
>
many_things: <
  [type.googleapis.com/testdata.MyMessage]: <
    count: 47
    name: "David"
    [testdata.Ext.more]: <
      data: "foo"
    >
    [testdata.Ext.text]: "bar"
  >
>
`
	)
	return []golden{
		{m1, strings.TrimSpace(m1Golden) + "\n", strings.TrimSpace(compact(m1Golden)) + " "},
		{m2, strings.TrimSpace(m2Golden) + "\n", strings.TrimSpace(compact(m2Golden)) + " "},
		{m3, strings.TrimSpace(m3Golden) + "\n", strings.TrimSpace(compact(m3Golden)) + " "},
		{m4, strings.TrimSpace(m4Golden) + "\n", strings.TrimSpace(compact(m4Golden)) + " "},
		{m5, strings.TrimSpace(m5Golden) + "\n", strings.TrimSpace(compact(m5Golden)) + " "},
		{m6, strings.TrimSpace(m6Golden) + "\n", strings.TrimSpace(compact(m6Golden)) + " "},
	}
}

func TestMarshalGolden(t *testing.T) {
	for _, tt := range goldenMessages {
		if got, want := expandedMarshaler.Text(tt.m), tt.t; got != want {
			t.Errorf("message %v: got:\n%s\nwant:\n%s", tt.m, got, want)
		}
		if got, want := expandedCompactMarshaler.Text(tt.m), tt.c; got != want {
			t.Errorf("message %v: got:\n`%s`\nwant:\n`%s`", tt.m, got, want)
		}
	}
}

func TestUnmarshalGolden(t *testing.T) {
	for _, tt := range goldenMessages {
		want := tt.m
		got := proto.Clone(tt.m)
		got.Reset()
		if err := proto.UnmarshalText(tt.t, got); err != nil {
			t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.t, err)
		}
		if !anyEqual(got, want) {
			t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.t, got, want)
		}
		got.Reset()
		if err := proto.UnmarshalText(tt.c, got); err != nil {
			t.Errorf("failed to unmarshal\n%s\nerror: %v", tt.c, err)
		}
		if !anyEqual(got, want) {
			t.Errorf("message:\n%s\ngot:\n%s\nwant:\n%s", tt.c, got, want)
		}
	}
}

func TestMarsahlUnknownAny(t *testing.T) {
	m := &pb.Message{
		Anything: &anypb.Any{
			TypeUrl: "foo",
			Value:   []byte("bar"),
		},
	}
	want := `anything: <
  type_url: "foo"
  value: "bar"
>
`
	got := expandedMarshaler.Text(m)
	if got != want {
		t.Errorf("got\n`%s`\nwant\n`%s`", got, want)
	}
}

func TestAmbiguousAny(t *testing.T) {
	pb := &anypb.Any{}
	err := proto.UnmarshalText(`
	[type.googleapis.com/proto3_proto.Nested]: <
	  bunny: "Monty"
	>
	type_url: "ttt/proto3_proto.Nested"
	`, pb)
	t.Logf("result: %v (error: %v)", expandedMarshaler.Text(pb), err)
	if err != nil {
		t.Errorf("failed to parse ambiguous Any message: %v", err)
	}
}


text:
module SpreeAmazonStyleLogin
  class Engine < Rails::Engine
    engine_name 'spree_amazon_style_login'

    config.autoload_paths += %W(#{config.root}/lib)

    # use rspec for tests
    config.generators do |g|
      g.test_framework :rspec
    end

    def self.activate
      Dir.glob(File.join(File.dirname(__FILE__), "../../app/**/*_decorator*.rb")) do |c|
        Rails.configuration.cache_classes ? require(c) : load(c)
      end
			Dir.glob(File.join(File.dirname(__FILE__), "../../app/overrides/**/*.rb")) do |c|
				Rails.application.config.cache_classes ? require(c) : load(c)
			end
    end

    config.to_prepare &method(:activate).to_proc
  end
end


text:
<BroadcastMonitor>
  <updated>2015-08-07T21:01:52</updated>
  <stationName>Radio 6</stationName>
  <Current>
    <startTime>2015-08-07T21:01:52</startTime>
    <itemId>1000080641:1244974</itemId>
    <titleId>216116485</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** WEEK 33 PRE-TOTH BO SARIS MORGEN</titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode>821</CategoryCode>
    <CategoryName>VANAF VOLGENDE WEEK</CategoryName>
    <itemDuration>7</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Current>
  <Next>
    <startTime>2015-08-07T21:01:56</startTime>
    <itemId>1000080641:1244975</itemId>
    <titleId>216114776</titleId>
    <itemCode></itemCode>
    <itemReference></itemReference>
    <titleName>*** TOTH RUBEN HEINS GUESTLIST</titleName>
    <artistName></artistName>
    <albumName></albumName>
    <CategoryCode>448</CategoryCode>
    <CategoryName>UUROPENERS</CategoryName>
    <itemDuration>14</itemDuration>
    <MultiMedia1></MultiMedia1>
    <MultiMedia2></MultiMedia2>
    <MultiMedia3></MultiMedia3>
    <MultiMedia4></MultiMedia4>
  </Next>
</BroadcastMonitor>


text:
<!DOCTYPE html>

		<meta charset="UTF-8" />
		<title>KStalk</title>

		<link href="assets/css/style.css" rel="stylesheet">

You're now up to date! :-)

What's new in v1.1.0?

Changed the UI of some windows (remove player, remove group, rename group)

The notification popup now shows the name of the server

New option: "Also notify when the player switches to another server"

Added the ability to add a batch of players to a group (instead of adding them one by one)

New option: "Run the application at system startup"

New option: "Start the application in a mimized state"

Fixed a lot minor bugs

Tweaking

			<button data-action="close" class="pull-bottom pull-center">Close</button>


text:
namespace EventCloud.Migrations
{
    using System;
    using System.Data.Entity.Migrations;

    public partial class Adde_Event_MaxRegistrationCount : DbMigration
    {
        public override void Up()
        {
            AddColumn("dbo.AppEvents", "MaxRegistrationCount", c => c.Int(nullable: false, defaultValue: 0));
        }

        public override void Down()
        {
            DropColumn("dbo.AppEvents", "MaxRegistrationCount");
        }
    }
}


text:
#ifndef _filter_h

#define _filter_h

#include <fromsys.h>
#include <banal.h>
#include <splitfields.h>
#include <datatypes.h>
#include <bufvec.h>
#include <cxops.h>
#include <fastrig.h>
#include <update.h>
#include <lmadf.h>
#include <fftw3.h>
#include <fftw3_fix.h>
#include <window.h>
#include <math.h>

typedef enum
{
  FIR_Undef, FIR_Lowpass, FIR_Bandpass, FIR_Highpass, FIR_Hilbert,
  FIR_Bandstop
} FIR_response_type;

typedef enum
{ FIR_Even, FIR_Odd } FIR_parity_type;

typedef struct _real_FIR
{
  REAL *coef;
  int size;
  FIR_response_type type;
  BOOLEAN cplx;
  struct
  {
    REAL lo, hi;
  } freq;
} RealFIRDesc, *RealFIR;

typedef struct _complex_FIR
{
  COMPLEX *coef;
  int size;
  FIR_response_type type;
  BOOLEAN cplx;
  struct
  {
    REAL lo, hi;
  } freq;
} ComplexFIRDesc, *ComplexFIR;

#define FIRcoef(p) ((p)->coef)
#define FIRtap(p, i) (FIRcoef(p)[(i)])
#define FIRsize(p) ((p)->size)
#define FIRtype(p) ((p)->type)
#define FIRiscomplex(p) ((p)->cplx)
#define FIRisreal(p) (!FIRiscomplex(p))
#define FIRfqlo(p) ((p)->freq.lo)
#define FIRfqhi(p) ((p)->freq.hi)

#define delFIR_Lowpass_REAL(p) delFIR_REAL(p)
#define delFIR_Lowpass_COMPLEX(p) delFIR_COMPLEX(p)
#define delFIR_Bandpass_REAL(p) delFIR_REAL(p)
#define delFIR_Bandpass_COMPLEX(p) delFIR_COMPLEX(p)
#define delFIR_Highpass_REAL(p) delFIR_REAL(p)
#define delFIR_Highpass_COMPLEX(p) delFIR_COMPLEX(p)
#define delFIR_Hilbert_REAL(p) delFIR_REAL(p)
#define delFIR_Hilbert_COMPLEX(p) delFIR_COMPLEX(p)
#define delFIR_Bandstop_REAL(p) delFIR_REAL(p)
#define delFIR_Bandstop_COMPLEX(p) delFIR_COMPLEX(p)

extern RealFIR newFIR_REAL (int size, char *tag);
extern ComplexFIR newFIR_COMPLEX (int size, char *tag);
extern void delFIR_REAL (RealFIR p);
extern void delFIR_COMPLEX (ComplexFIR p);
extern RealFIR newFIR_Lowpass_REAL (REAL cutoff, REAL sr, int size);
extern ComplexFIR newFIR_Lowpass_COMPLEX (REAL cutoff, REAL sr, int size);
extern RealFIR newFIR_Bandpass_REAL (REAL lo, REAL hi, REAL sr, int size);
extern ComplexFIR newFIR_Bandpass_COMPLEX (REAL lo, REAL hi, REAL sr,
					   int size);
extern RealFIR newFIR_Highpass_REAL (REAL cutoff, REAL sr, int size);
extern ComplexFIR newFIR_Highpass_COMPLEX (REAL cutoff, REAL sr, int size);
extern RealFIR newFIR_Hilbert_REAL (REAL lo, REAL hi, REAL sr, int size);
extern ComplexFIR newFIR_Hilbert_COMPLEX (REAL lo, REAL hi, REAL sr,
					  int size);
extern RealFIR newFIR_Bandstop_REAL (REAL lo, REAL hi, REAL sr, int size);
extern ComplexFIR newFIR_Bandstop_COMPLEX (REAL lo, REAL hi, REAL sr,
					   int size);

#endif


text:
"""Emacs and Flymake compatible Pylint.

This script is for integration with emacs and is compatible with flymake mode.

This version of epylint traverses out of packages before invoking pylint.  This avoids the reporting
of errors that occur when a module within package uses a full package import path to get hold of
another module within this package.

For example:
    - Suppose a package is structured as

        a/__init__.py
        a/b/x.py
        a/c/y.py

   - Then if y.py imports x as "from a.b import x" the following produces pylint errors

       cd a/c; pylint y.py

   - The following obviously doesn't

       pylint a/c/y.py

   - As this script will be invoked by emacs within the directory of the file we are checking
     we need to traverse down out of it to avoid these false positives.

You may also use py_run to run pylint with desired options and get back (or not) its output.
"""

import sys, os, re
from subprocess import Popen, PIPE

def lint(filename):
    """Pylint the given file.

    When run from emacs we will be in the directory of a file, and passed its filename.
    If this file is part of a package and is trying to import other modules from within
    its own package or another package rooted in a directory below it, pylint will classify
    it as a failed import.

    To get around this, we traverse down the directory tree to find the root of the package this
    module is in.  We then invoke pylint from this directory.

    Finally, we must correct the filenames in the output generated by pylint so Emacs doesn't
    become confused (it will expect just the original filename, while pylint may extend it with
    extra directories if we've traversed down the tree)
    """
    # traverse downwards until we are out of a python package
    fullPath = os.path.abspath(filename)
    parentPath, childPath = os.path.dirname(fullPath), os.path.basename(fullPath)

    while parentPath != "/" and os.path.exists(os.path.join(parentPath, '__init__.py')):
        childPath = os.path.join(os.path.basename(parentPath), childPath)
        parentPath = os.path.dirname(parentPath)

    # Start pylint
    process = Popen("pylint -f parseable -r n --disable-msg-cat=CRI '%s'" %
                    childPath, shell=True, stdout=PIPE, stderr=PIPE,
                    cwd=parentPath)
    p = process.stdout

    # The parseable line format is '%(path)s:%(line)s: [%(sigle)s%(obj)s] %(msg)s'
    # NOTE: This would be cleaner if we added an Emacs reporter to pylint.reporters.text ..
    regex = re.compile(r"\[(?P<type>[WE])(?P<remainder>.*?)\]")

    def _replacement(mObj):
        "Alter to include 'Error' or 'Warning'"
        if mObj.group("type") == "W":
            replacement = "Warning"
        else:
            replacement = "Error"
        # replace as "Warning (W0511, funcName): Warning Text"
        return "%s (%s%s):" % (replacement, mObj.group("type"), mObj.group("remainder"))

    for line in p:
        # remove pylintrc warning
        if line.startswith("No config file found"):
            continue
        line = regex.sub(_replacement, line, 1)
        # modify the file name thats output to reverse the path traversal we made
        parts = line.split(":")
        if parts and parts[0] == childPath:
            line = ":".join([filename] + parts[1:])
        print line,

    p.close()

def Run():
    lint(sys.argv[1])

def py_run(command_options='', return_std=False, stdout=None, stderr=None,
           script='pylint'):
    """Run pylint from python (needs Python >= 2.4).

    ``command_options`` is a string containing ``pylint`` command line options;
    ``return_std`` (boolean) indicates return of created standart output
    and error (see below);
    ``stdout`` and ``stderr`` are 'file-like' objects in which standart output
    could be written.

    Calling agent is responsible for stdout/err management (creation, close).
    Default standart output and error are those from sys,
    or standalone ones (``subprocess.PIPE``) are used
    if they are not set and ``return_std``.

    If ``return_std`` is set to ``True``, this function returns a 2-uple
    containing standart output and error related to created process,
    as follows: ``(stdout, stderr)``.

    A trivial usage could be as follows:
        >>> py_run( '--version')
        No config file found, using default configuration
        pylint 0.18.1,
            ...

    To silently run Pylint on a module, and get its standart output and error:
        >>> (pylint_stdout, pylint_stderr) = py_run( 'module_name.py', True)
    """
    # Create command line to call pylint
    if os.name == 'nt':
        script += '.bat'
    command_line = script + ' ' + command_options
    # Providing standart output and/or error if not set
    if stdout is None:
        if return_std:
            stdout = PIPE
        else:
            stdout = sys.stdout
    if stderr is None:
        if return_std:
            stderr = PIPE
        else:
            stderr = sys.stderr
    # Call pylint in a subprocess
    p = Popen(command_line, shell=True, stdout=stdout, stderr=stderr)
    p.wait()
    # Return standart output and error
    if return_std:
        return (p.stdout, p.stderr)

if __name__ == '__main__':
    lint(sys.argv[1])


text:
ACCEPTED

#### According to
Index Fungorum

#### Published in
Can. J. Bot. 31: 634 (1953)

#### Original name
Virgaria uniseptata Berk. & M.A. Curtis

### Remarks
null


text:
Database {{container.Name}}

				Schedules

				Users

				Access Rules

				Delete

				Failover

				Start

				Stop

				Monitor

bgwriter

databasesize

loadtest

pgstatreplication

pgcontroldata

pg_settings

pg_stat_database

pg_stat_statements

pgbadger


text:
/* MACHINE GENERATED FILE, DO NOT EDIT */

#include <jni.h>
#include "extgl.h"

typedef void (APIENTRY *glTextureRangeAPPLEPROC) (GLenum target, GLsizei length, GLvoid * pointer);
typedef void (APIENTRY *glGetTexParameterPointervAPPLEPROC) (GLenum target, GLenum pname, GLvoid ** params);

JNIEXPORT void JNICALL Java_org_lwjgl_opengl_APPLETextureRange_nglTextureRangeAPPLE(JNIEnv *env, jclass clazz, jint target, jint length, jlong pointer, jlong function_pointer) {
	GLvoid *pointer_address = (GLvoid *)(intptr_t)pointer;
	glTextureRangeAPPLEPROC glTextureRangeAPPLE = (glTextureRangeAPPLEPROC)((intptr_t)function_pointer);
	glTextureRangeAPPLE(target, length, pointer_address);
}

JNIEXPORT jobject JNICALL Java_org_lwjgl_opengl_APPLETextureRange_nglGetTexParameterPointervAPPLE(JNIEnv *env, jclass clazz, jint target, jint pname, jlong result_size, jlong function_pointer) {
	glGetTexParameterPointervAPPLEPROC glGetTexParameterPointervAPPLE = (glGetTexParameterPointervAPPLEPROC)((intptr_t)function_pointer);
	GLvoid * __result;
	glGetTexParameterPointervAPPLE(target, pname, &__result);
	return safeNewBuffer(env, __result, result_size);
}


text:
package cgta.ojs.lang

import scala.scalajs.js

//////////////////////////////////////////////////////////////
// Created by bjackman @ 12/10/13 9:33 PM
//////////////////////////////////////////////////////////////

object Optional {
  implicit class OptionalExtensions[A](val a: Optional[A]) extends AnyVal {
    def isNull = a == null
    def isUndefined = a.isInstanceOf[js.Undefined]
    def isEmpty = isNull || isUndefined
    def isNonEmpty = !isEmpty
    def get: A = if (isNonEmpty) a.asInstanceOf[A] else sys.error(s"get called on nullable when A is not defined")
    def toOption: Option[A] = if (isNonEmpty) Some(get) else None
  }
  implicit def AToOptional[A](a : A) = a.asInstanceOf[Optional[A]]
}

trait Optional[+A] extends js.Object


text:
{% extends 'civic_calendar/_base.html' %}

{% block content %}

                {% if user.is_authenticated %}Hello, {{ user.first_name }} {{ user.last_name }}!{% endif %}

                Add a meeting

        {% for event in event_list %}

Click to edit

{{ event.meeting_handle }}

Entity: {{ event.entity.name }}

Start: {{ event.start }}

Name: {{ event.location.name }}

Address: {{ event.location.address }}

City: {{ event.location.city }}

Agenda: {{ event.agenda }}

Website: {{ event.website }}

Contact email: {{ event.contact_email }}

Contact phone: {{ event.contact_phone }}

                    Entered by: {{ event.creator.first_name }} {{ event.creator.last_name }}

            Delete
        {% endfor %}

{% endblock content %}


text:
package org.codehaus.groovy.classgen.asm.sc;

import org.codehaus.groovy.ast.ClassHelper;
import org.codehaus.groovy.ast.ClassNode;
import org.codehaus.groovy.ast.MethodNode;
import org.codehaus.groovy.ast.Parameter;
import org.codehaus.groovy.ast.expr.Expression;
import org.codehaus.groovy.classgen.asm.BytecodeHelper;
import org.codehaus.groovy.syntax.RuntimeParserException;
import org.objectweb.asm.Handle;
import org.objectweb.asm.Opcodes;
import org.objectweb.asm.Type;

import java.util.Arrays;
import java.util.List;

import static org.codehaus.groovy.ast.ClassHelper.getUnwrapper;
import static org.codehaus.groovy.ast.ClassHelper.getWrapper;
import static org.codehaus.groovy.transform.stc.StaticTypesMarker.INFERRED_FUNCTIONAL_INTERFACE_TYPE;
import static org.codehaus.groovy.transform.stc.StaticTypesMarker.PARAMETER_TYPE;

/**
 * Represents functional interface writer which contains some common methods to complete generating bytecode
 * @since 3.0.0
 */
public interface AbstractFunctionalInterfaceWriter {
    String ORIGINAL_PARAMETERS_WITH_EXACT_TYPE = "__ORIGINAL_PARAMETERS_WITH_EXACT_TYPE";

    default ClassNode getFunctionalInterfaceType(Expression expression) {
        ClassNode type = expression.getNodeMetaData(PARAMETER_TYPE);

        if (null == type) {
            type = expression.getNodeMetaData(INFERRED_FUNCTIONAL_INTERFACE_TYPE);
        }
        return type;
    }

    default String createMethodDescriptor(MethodNode abstractMethodNode) {
        return BytecodeHelper.getMethodDescriptor(
                abstractMethodNode.getReturnType().getTypeClass(),
                Arrays.stream(abstractMethodNode.getParameters())
                        .map(e -> e.getType().getTypeClass())
                        .toArray(Class[]::new)
        );
    }

    default Handle createBootstrapMethod(boolean isInterface, boolean serializable) {
        if (serializable) {
            return new Handle(
                    Opcodes.H_INVOKESTATIC,
                    "java/lang/invoke/LambdaMetafactory",
                    "altMetafactory",
                    "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;[Ljava/lang/Object;)Ljava/lang/invoke/CallSite;",
                    isInterface
            );
        }

        return new Handle(
                Opcodes.H_INVOKESTATIC,
                "java/lang/invoke/LambdaMetafactory",
                "metafactory",
                "(Ljava/lang/invoke/MethodHandles$Lookup;Ljava/lang/String;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodType;Ljava/lang/invoke/MethodHandle;Ljava/lang/invoke/MethodType;)Ljava/lang/invoke/CallSite;",
                isInterface
        );
    }

    default Object[] createBootstrapMethodArguments(final String abstractMethodDesc, final int insn, final ClassNode methodOwner, final MethodNode methodNode, final boolean serializable) {
        Object[] arguments = !serializable ? new Object[3] : new Object[]{null, null, null, 5, 0};

        arguments[0] = Type.getType(abstractMethodDesc);

        arguments[1] = new Handle(
                insn, // H_INVOKESTATIC or H_INVOKEVIRTUAL or H_INVOKEINTERFACE (GROOVY-9853)
                BytecodeHelper.getClassInternalName(methodOwner.getName()),
                methodNode.getName(),
                BytecodeHelper.getMethodDescriptor(methodNode),
                methodOwner.isInterface());

        arguments[2] = Type.getType(
                BytecodeHelper.getMethodDescriptor(methodNode.getReturnType(),
                (Parameter[]) methodNode.getNodeMetaData(ORIGINAL_PARAMETERS_WITH_EXACT_TYPE)));

        return arguments;
    }

    default ClassNode convertParameterType(ClassNode targetType, ClassNode parameterType, ClassNode inferredType) {
        if (!getWrapper(inferredType).isDerivedFrom(getWrapper(parameterType))) {
            throw new RuntimeParserException("The inferred type[" + inferredType.redirect() + "] is not compatible with the parameter type[" + parameterType.redirect() + "]", parameterType);
        }

        ClassNode type;
        boolean isParameterTypePrimitive = ClassHelper.isPrimitiveType(parameterType);
        boolean isInferredTypePrimitive = ClassHelper.isPrimitiveType(inferredType);
        if (!isParameterTypePrimitive && isInferredTypePrimitive) {
            if (ClassHelper.isDynamicTyped(parameterType) && ClassHelper.isPrimitiveType(targetType) // (1)
                    || !parameterType.equals(getUnwrapper(parameterType)) && !inferredType.equals(getWrapper(inferredType)) // (2)
            ) {
                // GROOVY-9790: bootstrap method initialization exception raised when lambda parameter type is wrong
                // (1) java.lang.invoke.LambdaConversionException: Type mismatch for instantiated parameter 0: class java.lang.Integer is not a subtype of int
                // (2) java.lang.BootstrapMethodError: bootstrap method initialization exception
                type = inferredType;
            } else {
                // The non-primitive type and primitive type are not allowed to mix since Java 9+
                // java.lang.invoke.LambdaConversionException: Type mismatch for instantiated parameter 0: int is not a subtype of class java.lang.Object
                type = getWrapper(inferredType);
            }
        } else if (isParameterTypePrimitive && !isInferredTypePrimitive) {
            // The non-primitive type and primitive type are not allowed to mix since Java 9+
            // java.lang.invoke.LambdaConversionException: Type mismatch for instantiated parameter 0: class java.lang.Integer is not a subtype of int
            type = getUnwrapper(inferredType);
        } else {
            type = inferredType;
        }
        return type;
    }

    /**
     * @deprecated use {@link #convertParameterType(ClassNode, ClassNode, ClassNode)} instead
     */
    @Deprecated
    default ClassNode convertParameterType(ClassNode parameterType, ClassNode inferredType) {
        if (!ClassHelper.getWrapper(inferredType.redirect()).isDerivedFrom(ClassHelper.getWrapper(parameterType.redirect()))) {
            throw new RuntimeParserException("The inferred type[" + inferredType.redirect() + "] is not compatible with the parameter type[" + parameterType.redirect() + "]", parameterType);
        } else {
            boolean isParameterTypePrimitive = ClassHelper.isPrimitiveType(parameterType);
            boolean isInferredTypePrimitive = ClassHelper.isPrimitiveType(inferredType);
            ClassNode type;
            if (!isParameterTypePrimitive && isInferredTypePrimitive) {
                if (parameterType != ClassHelper.getUnwrapper(parameterType) && inferredType != ClassHelper.getWrapper(inferredType)) {
                    type = inferredType;
                } else {
                    type = ClassHelper.getWrapper(inferredType);
                }
            } else if (isParameterTypePrimitive && !isInferredTypePrimitive) {
                type = ClassHelper.getUnwrapper(inferredType);
            } else {
                type = inferredType;
            }

            return type;
        }
    }

    default Parameter prependParameter(List<Parameter> methodParameterList, String parameterName, ClassNode parameterType) {
        Parameter parameter = new Parameter(parameterType, parameterName);

        parameter.setOriginType(parameterType);
        parameter.setClosureSharedVariable(false);

        methodParameterList.add(0, parameter);

        return parameter;
    }
}


text:
using System;
using System.Collections.Generic;
using IMu;

namespace CollectionsOnline.Import.Infrastructure
{
    public class ImuSession : IDisposable
    {
        private Session _session;
        private Module _module;
        private bool _disposed;

        public ImuSession(string moduleName, string host, int port)
        {
            _session = new Session(host, port);
            _session.Connect();

            _module = new Module(moduleName, _session);
        }

        public long FindKey(long irn)
        {
            return _module.FindKey(irn);
        }

        public long FindKeys(List<long> keys)
        {
            return _module.FindKeys(keys);
        }

        public long FindTerms(Terms terms)
        {
            return _module.FindTerms(terms);
        }

        public ModuleFetchResult Fetch(string flag, int offset, int count, string[] columns)
        {
            return _module.Fetch(flag, offset, count, columns);
        }

        protected virtual void Dispose(bool disposing)
        {
            if (!_disposed)
            {
                if (disposing)
                {
                    // Dispose managed resources.
                    if (_session != null)
                    {
                        _session.Disconnect();
                        _session = null;
                    }
                }

                // Dispose unmanaged managed resources.
                _disposed = true;
                _module = null;
            }
        }

        public void Dispose()
        {
            Dispose(true);
            GC.SuppressFinalize(this);
        }
    }
}


text:
package javax.swing.plaf;

import java.awt.Insets;
import javax.swing.JMenuBar;

import javax.swing.JMenu;
/**
 * Pluggable look and feel interface for JMenuBar.
 *
 * @author Georges Saab
 * @author David Karlton
 */

public abstract class MenuBarUI extends ComponentUI {
    /**
     * Constructor for subclasses to call.
     */
    protected MenuBarUI() {}
}


text:
import Ember from 'ember';
import AuthRoute from '../mixins/auth-route';

export default Ember.Route.extend(AuthRoute, {
  model: function(){
    return this.store.find('log');
  }
});


text:
<?php

declare(strict_types=1);

namespace Eloquent\Phony\Hook;

use Eloquent\Phony\Hook\Exception\FunctionExistsException;
use Eloquent\Phony\Hook\Exception\FunctionHookException;
use Eloquent\Phony\Hook\Exception\FunctionHookGenerationFailedException;
use Eloquent\Phony\Hook\Exception\FunctionSignatureMismatchException;
use Eloquent\Phony\Invocation\InvocableInspector;
use Eloquent\Phony\Reflection\FunctionSignatureInspector;
use ParseError;

/**
 * Allows control over the behavior of function hooks.
 */
class FunctionHookManager
{
    /**
     * Get the static instance of this class.
     *
     * @return self The static instance.
     */
    public static function instance(): self
    {
        if (!self::$instance) {
            self::$instance = new self(
                InvocableInspector::instance(),
                FunctionSignatureInspector::instance(),
                FunctionHookGenerator::instance()
            );
        }

        return self::$instance;
    }

    /**
     * Construct a new function hook manager.
     *
     * @param InvocableInspector         $invocableInspector The invocable inspector to use.
     * @param FunctionSignatureInspector $signatureInspector The function signature inspector to use.
     * @param FunctionHookGenerator      $hookGenerator      The function hook generator to use.
     */
    public function __construct(
        InvocableInspector $invocableInspector,
        FunctionSignatureInspector $signatureInspector,
        FunctionHookGenerator $hookGenerator
    ) {
        $this->invocableInspector = $invocableInspector;
        $this->signatureInspector = $signatureInspector;
        $this->hookGenerator = $hookGenerator;
    }

    /**
     * Define the behavior of a function hook.
     *
     * @param string   $name      The function name.
     * @param string   $namespace The namespace.
     * @param callable $callback  The callback.
     *
     * @return ?callable             The replaced callback, or null if no callback was set.
     * @throws FunctionHookException If the function hook generation fails.
     */
    public function defineFunction(
        string $name,
        string $namespace,
        callable $callback
    ): ?callable {
        $signature = $this->signatureInspector->signature(
            $this->invocableInspector->callbackReflector($callback)
        );
        list($parameters) = $signature;
        $fullName = $namespace . '\\' . $name;
        $key = strtolower($fullName);

        if (isset(self::$hooks[$key])) {
            if ($parameters !== self::$hooks[$key]['signature']) {
                throw new FunctionSignatureMismatchException($fullName);
            }

            $replaced = self::$hooks[$key]['callback'];
        } else {
            $replaced = null;

            if (function_exists($fullName)) {
                throw new FunctionExistsException($fullName);
            }

            $source = $this->hookGenerator
                ->generateHook($name, $namespace, $signature);
            $reporting = error_reporting(E_ERROR | E_COMPILE_ERROR);

            try {
                eval($source);
            } catch (ParseError $e) {
                throw new FunctionHookGenerationFailedException(
                    $fullName,
                    $callback,
                    $source,
                    error_get_last(),
                    $e
                );
            } finally {
                error_reporting($reporting);
            }

            if (!function_exists($fullName)) {
                // @codeCoverageIgnoreStart
                throw new FunctionHookGenerationFailedException(
                    $fullName,
                    $callback,
                    $source,
                    error_get_last()
                );
                // @codeCoverageIgnoreEnd
            }
        }

        self::$hooks[$key] =
            ['callback' => $callback, 'signature' => $parameters];

        return $replaced;
    }

    /**
     * Effectively removes any function hooks for functions in the global
     * namespace.
     */
    public function restoreGlobalFunctions(): void
    {
        foreach (self::$hooks as $key => $data) {
            self::$hooks[$key]['callback'] = null;
        }
    }

    /**
     * @var array<string,array<string,mixed>>
     */
    public static $hooks = [];

    /**
     * @var ?self
     */
    private static $instance;

    /**
     * @var InvocableInspector
     */
    private $invocableInspector;

    /**
     * @var FunctionSignatureInspector
     */
    private $signatureInspector;

    /**
     * @var FunctionHookGenerator
     */
    private $hookGenerator;
}


text:
NSString *const kGPUImageTwoInputNearbyTexelSamplingVertexShaderString = SHADER_STRING
(
 attribute vec4 position;
 attribute vec4 inputTextureCoordinate;
 attribute vec4 inputTextureCoordinate2;

 uniform float texelWidth;
 uniform float texelHeight;

 varying vec2 textureCoordinate;
 varying vec2 leftTextureCoordinate;
 varying vec2 rightTextureCoordinate;
 varying vec2 topTextureCoordinate;
 varying vec2 bottomTextureCoordinate;

 varying vec2 textureCoordinate2;
 varying vec2 leftTextureCoordinate2;
 varying vec2 rightTextureCoordinate2;
 varying vec2 topTextureCoordinate2;
 varying vec2 bottomTextureCoordinate2;

 void main()
 {
     gl_Position = position;

     vec2 widthStep = vec2(texelWidth, 0.0);
     vec2 heightStep = vec2(0.0, texelHeight);

     textureCoordinate = inputTextureCoordinate.xy;
     leftTextureCoordinate = inputTextureCoordinate.xy - widthStep;
     rightTextureCoordinate = inputTextureCoordinate.xy + widthStep;
     topTextureCoordinate = inputTextureCoordinate.xy - heightStep;
     bottomTextureCoordinate = inputTextureCoordinate.xy + heightStep;

     textureCoordinate2 = inputTextureCoordinate2.xy;
     leftTextureCoordinate2 = inputTextureCoordinate2.xy - widthStep;
     rightTextureCoordinate2 = inputTextureCoordinate2.xy + widthStep;
     topTextureCoordinate2 = inputTextureCoordinate2.xy - heightStep;
     bottomTextureCoordinate2 = inputTextureCoordinate2.xy + heightStep;
 }
);

@implementation GPUImageTwoInputCrossTextureSamplingFilter

@synthesize texelWidth = _texelWidth;
@synthesize texelHeight = _texelHeight;

#pragma mark -
#pragma mark Initialization and teardown

- (id)initWithFragmentShaderFromString:(NSString *)fragmentShaderString;
{
    if (!(self = [super initWithVertexShaderFromString:kGPUImageTwoInputNearbyTexelSamplingVertexShaderString fragmentShaderFromString:fragmentShaderString]))
    {
        return nil;
    }

    texelWidthUniform = [filterProgram uniformIndex:@"texelWidth"];
    texelHeightUniform = [filterProgram uniformIndex:@"texelHeight"];

    return self;
}

- (void)setupFilterForSize:(CGSize)filterFrameSize;
{
    if (!hasOverriddenImageSizeFactor)
    {
        _texelWidth = 1.0 / filterFrameSize.width;
        _texelHeight = 1.0 / filterFrameSize.height;

        runSynchronouslyOnVideoProcessingQueue(^{
            [GPUImageContext setActiveShaderProgram:filterProgram];
            if (GPUImageRotationSwapsWidthAndHeight(inputRotation))
            {
                glUniform1f(texelWidthUniform, _texelHeight);
                glUniform1f(texelHeightUniform, _texelWidth);
            }
            else
            {
                glUniform1f(texelWidthUniform, _texelWidth);
                glUniform1f(texelHeightUniform, _texelHeight);
            }
        });
    }
}

#pragma mark -
#pragma mark Accessors

- (void)setTexelWidth:(CGFloat)newValue;
{
    hasOverriddenImageSizeFactor = YES;
    _texelWidth = newValue;

    [self setFloat:_texelWidth forUniform:texelWidthUniform program:filterProgram];
}

- (void)setTexelHeight:(CGFloat)newValue;
{
    hasOverriddenImageSizeFactor = YES;
    _texelHeight = newValue;

    [self setFloat:_texelHeight forUniform:texelHeightUniform program:filterProgram];
}

@end


text:
layout: nil
---
<?xml version='1.0' encoding='UTF-8'?>
<?compositeMetadataRepository version='1.0.0'?>
<repository name='Nodeclipse Updates - CSVEdit'
    type='org.eclipse.equinox.internal.p2.metadata.repository.CompositeMetadataRepository' version='1.0.0'>
  <properties size='1'>
    <!-- http://www.epochconverter.com/ or http://www.onlineconversion.com/unix_time.htm -->
    <property name='p2.timestamp' value='{% include p2.timestamp.txt %}'/>
  </properties>
  <children size='1'>
	<child location='https://dl.bintray.com/enide/CvsEdit/'/>
  </children>
</repository>


text:
require 'json'

class WelcomeController < ApplicationController
  def index
  end
end


text:
<?xml version="1.0" encoding="UTF-8"?>

<!DOCTYPE document PUBLIC "-//APACHE//DTD Documentation V2.0//EN" "http://forrest.apache.org/dtd/document-v20.dtd">
<document>

    <title>Welcome to the org.apache.forrest.plugin.input.Resume Plugin</title>

      <title>Apache Forrest - org.apache.forrest.plugin.input.Resume Plugin</title>

        Allows the use of documents conforming to the DTD's developed by
        http://xmlresume.sourceforge.net. Also includes transformations from an
        OpenOffice.org document to xmlresume format.

      <title>Samples</title>

        This section includes links to a number of samples using this plugin.
        The plugin is intended to be self documenting through these samples. If
        you requrie further help please ask on the user mailing list.

<fixme author="rdg">
            Add a link to a sample here...
          </fixme>

<fixme author="rdg">
            Add another sample link here...
          </fixme>

      <note>
        The more samples included here the easier it is for users to understand
        this plugin. If you can provide additional samples please do so.
      </note>

</document>


text:
package org.apache.servicecomb.faultinjection;

import static org.junit.Assert.assertEquals;

import org.junit.After;
import org.junit.Assert;
import org.junit.Before;
import org.junit.Test;

/**
 * Tests the fault injection configuration.
 */
public class TestFaultInjectConfig {
  FaultInjectionConfig faultCfg;

  FaultInjectionConst faultConst;

  FaultParam faultParam;

  AbortFault abortFault;

  DelayFault delayFault;

  @Before
  public void setUp() throws Exception {
    faultCfg = new FaultInjectionConfig();
    faultConst = new FaultInjectionConst();
    faultParam = new FaultParam(10);
    abortFault = new AbortFault();
    delayFault = new DelayFault();
  }

  @After
  public void tearDown() throws Exception {
    faultCfg = null;
    faultConst = null;
    faultParam = null;
  }

  @Test
  public void testFaultInjectConfig() throws Exception {
    int val = FaultInjectionConfig.getConfigVal("servicecomb.servicecomb.handler.consumer.faultinject.config", 0);
    Assert.assertEquals(0, val);
  }

  @Test
  public void testConstants() {
    assertEquals("servicecomb.governance.Consumer.", FaultInjectionConst.CONSUMER_FAULTINJECTION);
    assertEquals("policy.fault.protocols.", FaultInjectionConst.CONSUMER_FAULTINJECTION_POLICY_PROTOCOLS);
    assertEquals(-1, FaultInjectionConst.FAULT_INJECTION_DEFAULT_VALUE);
    assertEquals("servicecomb.governance.Consumer._global.", FaultInjectionConst.CONSUMER_FAULTINJECTION_GLOBAL);
    assertEquals(-1, FaultInjectionConst.FAULT_INJECTION_ERROR);
  }

  @Test
  public void testFaultParam() {
    faultParam.setReqCount(100);
    faultParam.setVertx(null);
    assertEquals(100, faultParam.getReqCount());
    assertEquals(null, faultParam.getVertx());
  }

  @Test
  public void testFaultPriority() {
    assertEquals(200, abortFault.getOrder());
    assertEquals(100, delayFault.getOrder());
  }
}


text:
using System;
using System.Drawing;
using System.Collections;
using System.ComponentModel;
using System.Windows.Forms;
using System.Data;
using System.Runtime.InteropServices;

//The interesting bit starts here

//note the order of these is important
public enum EncodingType
{
    UTF8 = 0,
    //UTF8WithPreamble,
    Unicode,
    Ansi
}

public class SaveFileDialogWithEncoding
{
    private delegate int OFNHookProcDelegate(int hdlg, int msg, int wParam, int lParam);

    private int m_LabelHandle = 0;
    private int m_ComboHandle = 0;

    private string m_Filter = "";
    private string m_DefaultExt = "";

    private string m_FileName = "";

    private EncodingType m_EncodingType;
    private Screen m_ActiveScreen;

    [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Auto)]
    private struct OPENFILENAME
    {
        public int lStructSize;
        public IntPtr hwndOwner;
        public int hInstance;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpstrFilter;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpstrCustomFilter;
        public int nMaxCustFilter;
        public int nFilterIndex;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpstrFile;
        public int nMaxFile;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpstrFileTitle;
        public int nMaxFileTitle;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpstrInitialDir;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpstrTitle;
        public int Flags;
        public short nFileOffset;
        public short nFileExtension;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpstrDefExt;
        public int lCustData;
        public OFNHookProcDelegate lpfnHook;
        [MarshalAs(UnmanagedType.LPTStr)]
        public string lpTemplateName;
        //only if on nt 5.0 or higher
        public int pvReserved;
        public int dwReserved;
        public int FlagsEx;
    }

    [DllImport("Comdlg32.dll", CharSet = CharSet.Auto, SetLastError = true)]
    private static extern bool GetSaveFileName(ref OPENFILENAME lpofn);

    [DllImport("Comdlg32.dll")]
    private static extern int CommDlgExtendedError();

    [DllImport("user32.dll")]
    private static extern bool SetWindowPos(int hWnd, int hWndInsertAfter, int X, int Y, int cx, int cy, uint uFlags);

    private struct RECT
    {
        public int Left;
        public int Top;
        public int Right;
        public int Bottom;
    }

    private struct POINT
    {
        public int X;
        public int Y;
    }

    private struct NMHDR
    {
        public int HwndFrom;
        public int IdFrom;
        public int Code;
    }

    [DllImport("user32.dll")]
    private static extern bool GetWindowRect(int hWnd, ref RECT lpRect);

    [DllImport("user32.dll")]
    private static extern int GetParent(int hWnd);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern bool SetWindowText(int hWnd, string lpString);

    [DllImport("user32.dll")]
    private static extern int SendMessage(int hWnd, int Msg, int wParam, int lParam);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern int SendMessage(int hWnd, int Msg, int wParam, string lParam);

    [DllImport("user32.dll")]
    private static extern bool DestroyWindow(int hwnd);

    private const int OFN_ENABLEHOOK = 0x00000020;
    private const int OFN_EXPLORER = 0x00080000;
    private const int OFN_FILEMUSTEXIST = 0x00001000;
    private const int OFN_HIDEREADONLY = 0x00000004;
    private const int OFN_CREATEPROMPT = 0x00002000;
    private const int OFN_NOTESTFILECREATE = 0x00010000;
    private const int OFN_OVERWRITEPROMPT = 0x00000002;
    private const int OFN_PATHMUSTEXIST = 0x00000800;

    private const int SWP_NOSIZE = 0x0001;
    private const int SWP_NOMOVE = 0x0002;
    private const int SWP_NOZORDER = 0x0004;

    private const int WM_INITDIALOG = 0x110;
    private const int WM_DESTROY = 0x2;
    private const int WM_SETFONT = 0x0030;
    private const int WM_GETFONT = 0x0031;

    private const int CBS_DROPDOWNLIST = 0x0003;
    private const int CBS_HASSTRINGS = 0x0200;
    private const int CB_ADDSTRING = 0x0143;
    private const int CB_SETCURSEL = 0x014E;
    private const int CB_GETCURSEL = 0x0147;

    private const uint WS_VISIBLE = 0x10000000;
    private const uint WS_CHILD = 0x40000000;
    private const uint WS_TABSTOP = 0x00010000;

    private const int CDN_FILEOK = 0;
    private const int WM_NOTIFY = 0x004E;

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern int GetDlgItem(int hDlg, int nIDDlgItem);

    [DllImport("user32.dll", CharSet = CharSet.Auto)]
    private static extern int CreateWindowEx(int dwExStyle, string lpClassName, string lpWindowName, uint dwStyle, int x, int y, int nWidth, int nHeight, int hWndParent, int hMenu, int hInstance, int lpParam);

    [DllImport("user32.dll")]
    private static extern bool ScreenToClient(int hWnd, ref POINT lpPoint);

    private int HookProc(int hdlg, int msg, int wParam, int lParam)
    {
        switch (msg)
        {
            case WM_INITDIALOG:

                //we need to centre the dialog
                Rectangle sr = m_ActiveScreen.Bounds;
                RECT cr = new RECT();
                int parent = GetParent(hdlg);
                GetWindowRect(parent, ref cr);

                int x = (sr.Right + sr.Left - (cr.Right - cr.Left)) / 2;
                int y = (sr.Bottom + sr.Top - (cr.Bottom - cr.Top)) / 2;

                SetWindowPos(parent, 0, x, y, cr.Right - cr.Left, cr.Bottom - cr.Top + 32, SWP_NOZORDER);

                //we need to find the label to position our new label under

                int fileTypeWindow = GetDlgItem(parent, 0x441);

                RECT aboveRect = new RECT();
                GetWindowRect(fileTypeWindow, ref aboveRect);

                //now convert the label's screen co-ordinates to client co-ordinates
                POINT point = new POINT();
                point.X = aboveRect.Left;
                point.Y = aboveRect.Bottom;

                ScreenToClient(parent, ref point);

                //create the label
                int labelHandle = CreateWindowEx(0, "STATIC", "mylabel", WS_VISIBLE | WS_CHILD | WS_TABSTOP, point.X, point.Y + 12, 200, 100, parent, 0, 0, 0);
                SetWindowText(labelHandle, "&Encoding:");

                int fontHandle = SendMessage(fileTypeWindow, WM_GETFONT, 0, 0);
                SendMessage(labelHandle, WM_SETFONT, fontHandle, 0);

                //we now need to find the combo-box to position the new combo-box under

                int fileComboWindow = GetDlgItem(parent, 0x470);
                aboveRect = new RECT();
                GetWindowRect(fileComboWindow, ref aboveRect);

                point = new POINT();
                point.X = aboveRect.Left;
                point.Y = aboveRect.Bottom;
                ScreenToClient(parent, ref point);

                POINT rightPoint = new POINT();
                rightPoint.X = aboveRect.Right;
                rightPoint.Y = aboveRect.Top;

                ScreenToClient(parent, ref rightPoint);

                //we create the new combobox

                int comboHandle = CreateWindowEx(0, "ComboBox", "mycombobox", WS_VISIBLE | WS_CHILD | CBS_HASSTRINGS | CBS_DROPDOWNLIST | WS_TABSTOP, point.X, point.Y + 8, rightPoint.X - point.X, 100, parent, 0, 0, 0);
                SendMessage(comboHandle, WM_SETFONT, fontHandle, 0);

                //and add the encodings we want to offer
                SendMessage(comboHandle, CB_ADDSTRING, 0, "UTF-8");
                //SendMessage(comboHandle, CB_ADDSTRING, 0, "UTF-8 with preamble");
                SendMessage(comboHandle, CB_ADDSTRING, 0, "Unicode");
                SendMessage(comboHandle, CB_ADDSTRING, 0, "ANSI");

                SendMessage(comboHandle, CB_SETCURSEL, (int)m_EncodingType, (int)m_EncodingType);

                //remember the handles of the controls we have created so we can destroy them after
                m_LabelHandle = labelHandle;
                m_ComboHandle = comboHandle;

                break;
            case WM_DESTROY:
                //destroy the handles we have created
                if (m_ComboHandle != 0)
                {
                    DestroyWindow(m_ComboHandle);
                }

                if (m_LabelHandle != 0)
                {
                    DestroyWindow(m_LabelHandle);
                }
                break;
            case WM_NOTIFY:

                //we need to intercept the CDN_FILEOK message
                //which is sent when the user selects a filename

                NMHDR nmhdr = (NMHDR)Marshal.PtrToStructure(new IntPtr(lParam), typeof(NMHDR));

                if (nmhdr.Code == CDN_FILEOK)
                {
                    //a file has been selected
                    //we need to get the encoding

                    m_EncodingType = (EncodingType)SendMessage(m_ComboHandle, CB_GETCURSEL, 0, 0);
                }
                break;

        }
        return 0;
    }

    public string DefaultExt
    {
        get
        {
            return m_DefaultExt;
        }
        set
        {
            m_DefaultExt = value;
        }
    }

    public string Filter
    {
        get
        {
            return m_Filter;
        }
        set
        {
            m_Filter = value;
        }
    }

    public string FileName
    {
        get
        {
            return m_FileName;
        }
        set
        {
            m_FileName = value;
        }
    }

    public EncodingType EncodingType
    {
        get
        {
            return m_EncodingType;
        }
        set
        {
            m_EncodingType = value;
        }
    }

    public DialogResult ShowDialog()
    {

        //set up the struct and populate it

        OPENFILENAME ofn = new OPENFILENAME();

        ofn.lStructSize = Marshal.SizeOf(ofn);
        ofn.lpstrFilter = m_Filter.Replace('|', '\0') + '\0';

        ofn.lpstrFile = m_FileName + new string(' ', 512);
        ofn.nMaxFile = ofn.lpstrFile.Length;
        ofn.lpstrFileTitle = System.IO.Path.GetFileName(m_FileName) + new string(' ', 512);
        ofn.nMaxFileTitle = ofn.lpstrFileTitle.Length;
        ofn.lpstrTitle = "Save file as";
        ofn.lpstrDefExt = m_DefaultExt;

        //position the dialog above the active window
        ofn.hwndOwner = Form.ActiveForm.Handle;

        //we need to find out the active screen so the dialog box is
        //centred on the correct display

        m_ActiveScreen = Screen.FromControl(Form.ActiveForm);

        //set up some sensible flags
        ofn.Flags = OFN_EXPLORER | OFN_PATHMUSTEXIST | OFN_NOTESTFILECREATE | OFN_ENABLEHOOK | OFN_HIDEREADONLY | OFN_OVERWRITEPROMPT;

        //this is where the hook is set. Note that we can use a C# delegate in place of a C function pointer
        ofn.lpfnHook = new OFNHookProcDelegate(HookProc);

        //if we're running on Windows 98/ME then the struct is smaller
        if (System.Environment.OSVersion.Platform != PlatformID.Win32NT)
        {
            ofn.lStructSize -= 12;
        }

        //show the dialog

        if (!GetSaveFileName(ref ofn))
        {
            int ret = CommDlgExtendedError();

            if (ret != 0)
            {
                throw new ApplicationException("Couldn't show file open dialog - " + ret.ToString());
            }

            return DialogResult.Cancel;
        }

        m_FileName = ofn.lpstrFile;

        return DialogResult.OK;
    }
}


text:
<?php
namespace Craft;

class InstaCraft_FileModel extends BaseModel
{
    /**
     * The defineAttributes of the InstaCraft_FileModel
     * @return array A folderId of the instagram url to go to
     */
    public function defineAttributes()
    {
        return array(
            'folderId' => AttributeType::Number,
            'imageId' => AttributeType::String,
            'url' => AttributeType::String,
            'text' => AttributeType::String,
        );
    }
}